| id | chat_gpt_response | question | badsmell_base | bad_smell_gpt | found_any | valid_bad_smell | bad_smell_in_base | bad_smell_not_in_the_base | bad_smell_not_found | index | index_base | url_github | nr_question | id_source_code | id_base |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2 | {"message":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
data class | long method, data class | t | t | t | long method | 0 | 529 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 1 | 2 | 529 | |
| 2 | {"YES I found bad smells":"the bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 529 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 2 | 2 | 529 |
| 4 | {"response":"YES I found bad smells","bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 555 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 1 | 4 | 555 |
| 4 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Long parameter list", "Data class", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
data class | 'Long method', 'Long parameter list', 'Data class', 'Feature envy' | t | t | f | {',L,o,n,g," ",m,e,t,h,o,d,',","," ",',L,o,n,g," ",p,a,r,a,m,e,t,e,r," ",l,i,s,t,',","," ",',D,a,t,a," ",c,l,a,s,s,',","," ",',F,e,a,t,u,r,e," ",e,n,v,y,'} | {',o,n,g," ",m,t,h,o,d,',","," ",',o,n,g," ",p,r,m,t,r," ",i,t,',","," ",',D,t," ",c,',","," ",',t,u,r," ",n,v,y,'} | 0 | 555 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 2 | 4 | 555 |
| 5 | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | f | f | f | long method | 0 | 565 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 1 | 5 | 565 | |||
| 5 | {"message": "YES I found bad smells. the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | Not specified | f | f | f | false | 0 | 565 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 2 | 5 | 565 | |
| 6 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 570 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 1 | 6 | 570 |
| 6 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
feature envy | long method, duplicate code | t | t | f | long method, duplicate code | feature envy | 0 | 570 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 2 | 6 | 570 |
| 7 | { "output": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | Not specified | f | f | f | false | 0 | 573 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 2 | 7 | 573 | |
| 7 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 573 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 1 | 7 | 573 |
| 9 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 612 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 2 | 9 | 612 | |
| 9 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
long method | long method | t | t | t | 0 | 612 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 1 | 9 | 612 | ||
| 10 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
feature envy | Not specified | f | f | f | false | 0 | 613 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 2 | 10 | 613 | |
| 10 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 613 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 1 | 10 | 613 |
| 12 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 619 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 2 | 12 | 619 |
| 13 | {"message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 622 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 13 | 622 | |
| 14 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | Not specified | f | f | f | false | 0 | 623 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 14 | 623 | |
| 15 | {"message": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy."} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static String replaceSubstitution(String base, Pattern from, String to, boolean repeat) { Matcher match = from.matcher(base); if (repeat) { return match.replaceAll(to); } else { return match.replaceFirst(to); } } |
feature envy | 1. long method, 2. feature envy. | t | t | t | 1. long method | 0 | 641 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KerberosName.java/#L287-L295 | 2 | 15 | 641 | |
| 16 | { "answer": "YES I found bad smells", "the bad smells are": "Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | data class | t | t | t | 0 | 642 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 16 | 642 | ||
| 16 | {"error": "Exceeded maximum character limit. Please shorten your request and try again."} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | Not specified | f | f | f | false | 0 | 642 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 16 | 642 | |
| 19 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int getSiblingIndexWithClassName(Element element, String className) { int index = 0; while (element != null) { element = (Element) element.getPreviousSibling(); if (element != null && Elements.hasClassName(className, element)) { ++index; } } return index; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 679 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/util/dom/DomUtils.java/#L171-L180 | 2 | 19 | 679 |
| 19 | {"response": "YES I found bad smells", "detected_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int getSiblingIndexWithClassName(Element element, String className) { int index = 0; while (element != null) { element = (Element) element.getPreviousSibling(); if (element != null && Elements.hasClassName(className, element)) { ++index; } } return index; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 679 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/util/dom/DomUtils.java/#L171-L180 | 1 | 19 | 679 | |
| 20 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | data class | t | t | t | 0 | 681 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 1 | 20 | 681 | ||
| 20 | {"response": "YES I found bad smells", "message": "the bad smells are:", "bad_smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 681 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 2 | 20 | 681 |
| 21 | { "answer": "YES I found bad smells", "bad smells are": "1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | 1. long method | t | t | t | 0 | 682 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 21 | 682 | ||
| 21 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | long method, data class | t | t | t | data class | 0 | 682 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 21 | 682 | |
| 22 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void hide() { view.close(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 686 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/progressor/ProgressMonitorPresenter.java/#L74-L76 | 1 | 22 | 686 |
| 22 | { "response": "YES I found bad smells the bad smells are: 1. Long method" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void hide() { view.close(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 686 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/progressor/ProgressMonitorPresenter.java/#L74-L76 | 2 | 22 | 686 |
| 24 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 691 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 24 | 691 |
| 25 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Key)) { return false; } Key key = (Key) o; return annotationType.equals(key.annotationType) && type.equals(key.type); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 693 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/commons/che-core-commons-inject/src/main/java/org/eclipse/che/inject/lifecycle/LifecycleModule.java/#L40-L50 | 1 | 25 | 693 |
| 25 | {"response": "YES, I found bad smells. The bad smells are: 1.Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Key)) { return false; } Key key = (Key) o; return annotationType.equals(key.annotationType) && type.equals(key.type); } |
feature envy | 1.long method | t | t | f | 1.long method | feature envy | 0 | 693 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/commons/che-core-commons-inject/src/main/java/org/eclipse/che/inject/lifecycle/LifecycleModule.java/#L40-L50 | 2 | 25 | 693 |
| 26 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 2 | 26 | 695 |
| 26 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are:": [ "1. Long Method", "2. Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | the bad smells are:: 1. long method, 2. data class | t | t | t | the bad smells are:: 1. long method | 0 | 695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 1 | 26 | 695 | |
| 28 | { "message": "NO, I did not find any bad smell" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 712 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 2 | 28 | 712 | ||
| 28 | { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | data class, long method | t | t | t | data class | 0 | 712 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 28 | 712 | |
| 30 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | data class, long method | t | t | t | long method | 0 | 719 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 30 | 719 | |
| 30 | {"response": "YES I found bad smells", "bad smells are": ["Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 719 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 30 | 719 |
| 31 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void displayWarning(final String message) { notificationMessage.showNotification(SPUIStyleDefinitions.SP_NOTIFICATION_WARNING_MESSAGE_STYLE, null, message, true); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 729 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/UINotification.java/#L52-L55 | 1 | 31 | 729 |
| 31 | { "message": "YES I found bad smells. The bad smells are: 1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void displayWarning(final String message) { notificationMessage.showNotification(SPUIStyleDefinitions.SP_NOTIFICATION_WARNING_MESSAGE_STYLE, null, message, true); } |
feature envy | Not specified | f | f | f | false | 0 | 729 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/UINotification.java/#L52-L55 | 2 | 31 | 729 | |
| 32 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | data class | t | t | t | 0 | 730 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 1 | 32 | 730 | ||
| 32 | {"message": "YES, I found bad smells. the bad smells are:", "bad_smells": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 730 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 2 | 32 | 730 |
| 33 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | long method | t | t | f | long method | data class | 0 | 732 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 1 | 33 | 732 |
| 33 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 732 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 33 | 732 |
| 34 | { "message": "YES, I found bad smells", "bad smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 742 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 34 | 742 | |
| 34 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 742 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 34 | 742 | |
| 35 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | 1. long method | t | t | t | 0 | 743 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 35 | 743 | ||
| 35 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 743 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 35 | 743 | |
| 36 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unused") private String format(String s, Object[] arguments) { if (arguments == null) { return s; } // A very simple implementation of format int i = 0; while (i < arguments.length) { String delimiter = "{" + i + "}"; while (s.contains(delimiter)) { s = s.replace(delimiter, String.valueOf(arguments[i])); } i++; } return s; } |
long method | long method | t | t | t | 0 | 754 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/GwtKuraException.java/#L148-L165 | 1 | 36 | 754 | ||
| 36 |
{ "response": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unused") private String format(String s, Object[] arguments) { if (arguments == null) { return s; } // A very simple implementation of format int i = 0; while (i < arguments.length) { String delimiter = "{" + i + "}"; while (s.contains(delimiter)) { s = s.replace(delimiter, String.valueOf(arguments[i])); } i++; } return s; } |
long method | long method | t | t | t | 0 | 754 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/GwtKuraException.java/#L148-L165 | 2 | 36 | 754 | ||
| 38 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOG.info("GroupService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteGroupByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 761 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java/#L203-L212 | 1 | 38 | 761 |
| 38 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOG.info("GroupService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteGroupByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 761 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java/#L203-L212 | 2 | 38 | 761 | |
| 40 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 769 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 1 | 40 | 769 |
| 40 | {"message": "YES I found bad smells. the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 769 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 2 | 40 | 769 |
| 42 | { "error": "Please provide a code snippet for analysis." } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
feature envy | Not specified | f | f | f | false | 0 | 805 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 42 | 805 | |
| 42 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 805 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 42 | 805 |
| 44 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Bundle[] getFragments(Bundle bundle) { if (packageAdmin == null) throw new IllegalStateException("Not started"); //$NON-NLS-1$ return packageAdmin.getFragments(bundle); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 830 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.equinox.jsp.jasper/src/org/eclipse/equinox/internal/jsp/jasper/Activator.java/#L71-L76 | 2 | 44 | 830 | |
| 44 | { "message": "YES, I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Bundle[] getFragments(Bundle bundle) { if (packageAdmin == null) throw new IllegalStateException("Not started"); //$NON-NLS-1$ return packageAdmin.getFragments(bundle); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 830 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.equinox.jsp.jasper/src/org/eclipse/equinox/internal/jsp/jasper/Activator.java/#L71-L76 | 1 | 44 | 830 |
| 45 | { "message": "YES, I found bad smells", "bad smells are": "1. Long method, 2. Feature envy" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final static class TypeList { Hashtable types; TypeList() { } TypeList(Vector typeNames) { types = new Hashtable(); for ( int i = 0; i < typeNames.size(); i++ ) { String t = ((String) typeNames.elementAt(i)).toLowerCase(); types.put(t, t); } } final boolean contains(String type) { if ( types == null ) { return true; //defaults to all } return types.containsKey(type); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 833 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.traceformat/share/classes/com/ibm/jvm/format/Util.java/#L631-L655 | 2 | 45 | 833 |
| 45 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final static class TypeList { Hashtable types; TypeList() { } TypeList(Vector typeNames) { types = new Hashtable(); for ( int i = 0; i < typeNames.size(); i++ ) { String t = ((String) typeNames.elementAt(i)).toLowerCase(); types.put(t, t); } } final boolean contains(String type) { if ( types == null ) { return true; //defaults to all } return types.containsKey(type); } } |
data class | data class | t | t | t | 0 | 833 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.traceformat/share/classes/com/ibm/jvm/format/Util.java/#L631-L655 | 1 | 45 | 833 | ||
| 46 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public UDATA add(UDATA parameter) { return new UDATA(this).add(parameter); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 835 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/types/U32.java/#L70-L72 | 2 | 46 | 835 | |
| 48 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | long method | t | t | t | 0 | 854 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 1 | 48 | 854 | ||
| 48 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Repeated code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | long method, repeated code | t | t | t | repeated code | 0 | 854 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 2 | 48 | 854 | |
| 50 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRegistry public class ObjectFactory { /** * Create an instance of {@link LWM2M } * */ public LWM2M createLWM2M() { return new LWM2M(); } /** * Create an instance of {@link LWM2M.Object } * */ public LWM2M.Object createLWM2MObject() { return new LWM2M.Object(); } /** * Create an instance of {@link LWM2M.Object.Resources } * */ public LWM2M.Object.Resources createLWM2MObjectResources() { return new LWM2M.Object.Resources(); } /** * Create an instance of {@link LWM2M.Object.Resources.Item } * */ public LWM2M.Object.Resources.Item createLWM2MObjectResourcesItem() { return new LWM2M.Object.Resources.Item(); } } |
data class | long method | t | t | f | long method | data class | 0 | 866 | https://github.com/eclipse/vorto/blob/93919469e598ec07fed134536b901efd25cf674f/repository/repository-importer/importer-ipso/src/main/java/org/eclipse/vorto/repository/importer/ipso/ObjectFactory.java/#L37-L72 | 1 | 50 | 866 |
| 50 | { "response": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRegistry public class ObjectFactory { /** * Create an instance of {@link LWM2M } * */ public LWM2M createLWM2M() { return new LWM2M(); } /** * Create an instance of {@link LWM2M.Object } * */ public LWM2M.Object createLWM2MObject() { return new LWM2M.Object(); } /** * Create an instance of {@link LWM2M.Object.Resources } * */ public LWM2M.Object.Resources createLWM2MObjectResources() { return new LWM2M.Object.Resources(); } /** * Create an instance of {@link LWM2M.Object.Resources.Item } * */ public LWM2M.Object.Resources.Item createLWM2MObjectResourcesItem() { return new LWM2M.Object.Resources.Item(); } } |
data class | long method | t | t | f | long method | data class | 0 | 866 | https://github.com/eclipse/vorto/blob/93919469e598ec07fed134536b901efd25cf674f/repository/repository-importer/importer-ipso/src/main/java/org/eclipse/vorto/repository/importer/ipso/ObjectFactory.java/#L37-L72 | 2 | 50 | 866 |
| 53 | { "response": "YES, I found bad smells", "bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout) throws IOException { final ProxyParams proxyParams = prepareProxyParams(); return executeUrl(httpMethod, url, httpHeaders, content, contentType, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 879 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/io/org.eclipse.smarthome.io.net/src/main/java/org/eclipse/smarthome/io/net/http/HttpUtil.java/#L127-L133 | 2 | 53 | 879 | |
| 53 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout) throws IOException { final ProxyParams proxyParams = prepareProxyParams(); return executeUrl(httpMethod, url, httpHeaders, content, contentType, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 879 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/io/org.eclipse.smarthome.io.net/src/main/java/org/eclipse/smarthome/io/net/http/HttpUtil.java/#L127-L133 | 1 | 53 | 879 |
| 54 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | long method | t | t | f | long method | data class | 0 | 953 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 2 | 54 | 953 |
| 54 | {"response": "YES I found bad smells, the bad smells are: 3. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | 3. data class | t | t | t | 0 | 953 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 1 | 54 | 953 | ||
| 57 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean hasMatchingKey(Node model1, Node model2) { return keyProvider.getKey(model1).equals(keyProvider.getKey(model2)); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 987 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/NodeStorage.java/#L626-L628 | 2 | 57 | 987 | |
| 57 | { "output": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean hasMatchingKey(Node model1, Node model2) { return keyProvider.getKey(model1).equals(keyProvider.getKey(model2)); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 987 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/NodeStorage.java/#L626-L628 | 1 | 57 | 987 | |
| 58 | {"response": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue abstract class UOfKind extends UExpression { public static UOfKind create(UExpression expression, Set allowed) { return new AutoValue_UOfKind(expression, allowed); } abstract UExpression expression(); abstract Set allowed(); @Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { return expression().inline(inliner); } @Override public R accept(TreeVisitor visitor, D data) { return expression().accept(visitor, data); } @Override public Kind getKind() { return expression().getKind(); } @Override @Nullable protected Choice defaultAction(Tree tree, @Nullable Unifier unifier) { return Choice.condition(allowed().contains(tree.getKind()), unifier) .thenChoose(unifications(expression(), tree)); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 988 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/refaster/UOfKind.java/#L33-L64 | 2 | 58 | 988 |
| 59 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Not specified | f | f | f | false | 0 | 1004 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 59 | 1004 | |
| 61 | { "answer": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } |
long method | 1. long method | t | t | t | 0 | 1020 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L473-L485 | 1 | 61 | 1020 | ||
| 61 | { "response": { "message": "YES, I found bad smells", "bad_smells": { "1. Long method": "The readNullTerminatedString method is quite lengthy.", "2. Feature envy": "The method seems to be more concerned with data fields than its own scope." } } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } |
long method | Not specified | f | f | f | false | 0 | 1020 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L473-L485 | 2 | 61 | 1020 | |
| 62 | { "message": "YES I found bad smells", "detected bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue.Builder public abstract static class Builder { public abstract Builder setCompileTimeConstant(boolean compileTimeConstant); public abstract Builder setStatic(boolean isStatic); public abstract Builder setFinal(boolean isFinal); public abstract Builder setVariableCapture(boolean isVariableCapture); public abstract Builder setEnclosingInstanceCapture(boolean isEnclosingInstanceCapture); public abstract Builder setEnclosingTypeDescriptor( DeclaredTypeDescriptor enclosingTypeDescriptor); public abstract Builder setName(String name); public abstract Builder setEnumConstant(boolean isEnumConstant); public abstract Builder setSynthetic(boolean isSynthetic); public abstract Builder setTypeDescriptor(TypeDescriptor typeDescriptor); public abstract Builder setVisibility(Visibility visibility); public abstract Builder setJsInfo(JsInfo jsInfo); public abstract Builder setUnusableByJsSuppressed(boolean isUnusableByJsSuppressed); public abstract Builder setDeprecated(boolean isDeprecated); public abstract Builder setOrigin(FieldOrigin fieldOrigin); public Builder setDeclarationFieldDescriptor(FieldDescriptor declarationFieldDescriptor) { return setDeclarationFieldDescriptorOrNullIfSelf(declarationFieldDescriptor); } // Accessors to support validation, default construction and custom setters. abstract Builder setDeclarationFieldDescriptorOrNullIfSelf( FieldDescriptor declarationFieldDescriptor); abstract Optional getName(); abstract FieldDescriptor autoBuild(); public FieldDescriptor build() { checkState(getName().isPresent()); FieldDescriptor fieldDescriptor = autoBuild(); checkState( !fieldDescriptor.isVariableCapture() || !fieldDescriptor.isEnclosingInstanceCapture()); return interner.intern(fieldDescriptor); } public static Builder from(FieldDescriptor fieldDescriptor) { return fieldDescriptor.toBuilder(); } private static final ThreadLocalInterner interner = new ThreadLocalInterner<>(); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1048 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/ast/FieldDescriptor.java/#L194-L255 | 2 | 62 | 1048 |
| 63 | {"response": "YES I found bad smells", "bad smells are": "1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1067 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 63 | 1067 |
| 63 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1067 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 63 | 1067 |
| 66 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Solaris extends OperatingSystem.Unix { @Override public String getFamilyName() { return "solaris"; } @Override protected String getOsPrefix() { return "sunos"; } @Override protected String getArch() { String arch = System.getProperty("os.arch"); if (arch.equals("i386") || arch.equals("x86")) { return "x86"; } return super.getArch(); } } |
data class | long method | t | t | f | long method | data class | 0 | 1074 | https://github.com/linkedin/pygradle/blob/4b04b7980dc47a76b816184ebbcfe0b3f5cefadd/pygradle-plugin/src/main/groovy/com/linkedin/gradle/python/util/OperatingSystem.java/#L363-L382 | 1 | 66 | 1074 |
| 66 | {"response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Solaris extends OperatingSystem.Unix { @Override public String getFamilyName() { return "solaris"; } @Override protected String getOsPrefix() { return "sunos"; } @Override protected String getArch() { String arch = System.getProperty("os.arch"); if (arch.equals("i386") || arch.equals("x86")) { return "x86"; } return super.getArch(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1074 | https://github.com/linkedin/pygradle/blob/4b04b7980dc47a76b816184ebbcfe0b3f5cefadd/pygradle-plugin/src/main/groovy/com/linkedin/gradle/python/util/OperatingSystem.java/#L363-L382 | 2 | 66 | 1074 |
| 71 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XPathConstants { /** * Private constructor to prevent instantiation. */ private XPathConstants() { } /** * The XPath 1.0 number data type. * * Maps to Java {@link Double}. */ public static final QName NUMBER = new QName("http://www.w3.org/1999/XSL/Transform", "NUMBER"); /** * The XPath 1.0 string data type. * * Maps to Java {@link String}. */ public static final QName STRING = new QName("http://www.w3.org/1999/XSL/Transform", "STRING"); /** * The XPath 1.0 boolean data type. * * Maps to Java {@link Boolean}. */ public static final QName BOOLEAN = new QName("http://www.w3.org/1999/XSL/Transform", "BOOLEAN"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.NodeList}. */ public static final QName NODESET = new QName("http://www.w3.org/1999/XSL/Transform", "NODESET"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.Node}. */ public static final QName NODE = new QName("http://www.w3.org/1999/XSL/Transform", "NODE"); /** * The URI for the DOM object model, "http://java.sun.com/jaxp/xpath/dom". */ public static final String DOM_OBJECT_MODEL = "http://java.sun.com/jaxp/xpath/dom"; } |
data class | long method | t | t | f | long method | data class | 0 | 1103 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/xpath/XPathConstants.java/#L32-L78 | 2 | 71 | 1103 |
| 71 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XPathConstants { /** * Private constructor to prevent instantiation. */ private XPathConstants() { } /** * The XPath 1.0 number data type. * * Maps to Java {@link Double}. */ public static final QName NUMBER = new QName("http://www.w3.org/1999/XSL/Transform", "NUMBER"); /** * The XPath 1.0 string data type. * * Maps to Java {@link String}. */ public static final QName STRING = new QName("http://www.w3.org/1999/XSL/Transform", "STRING"); /** * The XPath 1.0 boolean data type. * * Maps to Java {@link Boolean}. */ public static final QName BOOLEAN = new QName("http://www.w3.org/1999/XSL/Transform", "BOOLEAN"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.NodeList}. */ public static final QName NODESET = new QName("http://www.w3.org/1999/XSL/Transform", "NODESET"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.Node}. */ public static final QName NODE = new QName("http://www.w3.org/1999/XSL/Transform", "NODE"); /** * The URI for the DOM object model, "http://java.sun.com/jaxp/xpath/dom". */ public static final String DOM_OBJECT_MODEL = "http://java.sun.com/jaxp/xpath/dom"; } |
data class | data class | t | t | t | 0 | 1103 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/xpath/XPathConstants.java/#L32-L78 | 1 | 71 | 1103 | ||
| 72 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1106 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 2 | 72 | 1106 |
| 72 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | data class | t | t | t | 0 | 1106 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 1 | 72 | 1106 | ||
| 73 | {"answer":"YES I found bad smells","detectedBadSmells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | long method, data class | t | t | t | long method | 0 | 1109 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 1 | 73 | 1109 | |
| 73 | { "message": "YES, I found bad smells", "the bad smells are": [ "1. Long class", "2. Long method", "3. Feature envy", "4. Data class", "5. Message chains", "6. Shotgun surgery", "7. Comments", "8. Data clumps" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | 1. long class, 2. long method, 3. feature envy, 4. data class, 5. message chains, 6. shotgun surgery, 7. comments, 8. data clumps | t | t | t | 1. long class, 2. long method, 3. feature envy, 5. message chains, 6. shotgun surgery, 7. comments, 8. data clumps | 0 | 1109 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 2 | 73 | 1109 | |
| 75 | {"error": "Unsupported text format for the request. Please provide the input in plain text format."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class State { public Map properties = new HashMap(); public Map array_properties = new HashMap(); } |
data class | Not specified | f | f | f | false | 0 | 1125 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/intellij/ApplicationSettings.java/#L58-L61 | 1 | 75 | 1125 | |
| 75 | { "message": "YES, I found bad smells", "bad smells are": [ "Use of raw type", "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class State { public Map properties = new HashMap(); public Map array_properties = new HashMap(); } |
data class | use of raw type, long method | t | t | f | use of raw type, long method | data class | 0 | 1125 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/intellij/ApplicationSettings.java/#L58-L61 | 2 | 75 | 1125 |
| 76 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(ListBootVolumeAttachmentsResponse o) { opcNextPage(o.getOpcNextPage()); opcRequestId(o.getOpcRequestId()); items(o.getItems()); return this; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1158 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-core/src/main/java/com/oracle/bmc/core/responses/ListBootVolumeAttachmentsResponse.java/#L33-L45 | 2 | 76 | 1158 |
| 76 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(ListBootVolumeAttachmentsResponse o) { opcNextPage(o.getOpcNextPage()); opcRequestId(o.getOpcRequestId()); items(o.getItems()); return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 1158 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-core/src/main/java/com/oracle/bmc/core/responses/ListBootVolumeAttachmentsResponse.java/#L33-L45 | 1 | 76 | 1158 |
| 78 | {"message": "NO, I did not find any bad smell"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | f | f | f | data class | 0 | 1160 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 78 | 1160 | ||
| 78 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | data class | t | t | t | 0 | 1160 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 78 | 1160 | ||
| 79 | {"message": "YES I found bad smells", "bad smells are": [ "1. Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private final static class DuplicatableProgressTrackingInputStream extends ProgressTrackingInputStream implements DuplicatableInputStream { private DuplicatableProgressTrackingInputStream( final InputStream source, final ProgressTracker progressTracker) { super(source, progressTracker); if (!(source instanceof DuplicatableInputStream)) { throw new IllegalStateException("Source MUST be a DuplicatableInputStream"); } } /** * The progress tracking input stream resulting from this call will re-use the progress tracker from the parent * progress tracking input stream after resetting it, thus invalidating the progress tracked by the parent * stream until now. To ensure correctness of the progress tracking functionality, do NOT read from the parent * stream after duplicating from it. * @return The duplicated progress tracking input stream. */ @Override public InputStream duplicate() { return ProgressTrackingInputStreamFactory.create( ((DuplicatableInputStream) getSource()).duplicate(), getProgressTracker().reset()); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1169 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-extensions/src/main/java/com/oracle/bmc/objectstorage/transfer/ProgressTrackingInputStreamFactory.java/#L95-L120 | 2 | 79 | 1169 |
| 79 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private final static class DuplicatableProgressTrackingInputStream extends ProgressTrackingInputStream implements DuplicatableInputStream { private DuplicatableProgressTrackingInputStream( final InputStream source, final ProgressTracker progressTracker) { super(source, progressTracker); if (!(source instanceof DuplicatableInputStream)) { throw new IllegalStateException("Source MUST be a DuplicatableInputStream"); } } /** * The progress tracking input stream resulting from this call will re-use the progress tracker from the parent * progress tracking input stream after resetting it, thus invalidating the progress tracked by the parent * stream until now. To ensure correctness of the progress tracking functionality, do NOT read from the parent * stream after duplicating from it. * @return The duplicated progress tracking input stream. */ @Override public InputStream duplicate() { return ProgressTrackingInputStreamFactory.create( ((DuplicatableInputStream) getSource()).duplicate(), getProgressTracker().reset()); } } |
data class | long method, data class | t | t | t | long method | 0 | 1169 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-extensions/src/main/java/com/oracle/bmc/objectstorage/transfer/ProgressTrackingInputStreamFactory.java/#L95-L120 | 1 | 79 | 1169 | |
| 80 | { "response": "YES I found bad smells", "bad smells are": [ "1.Long method", "2.Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | data class | 0 | 1185 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 2 | 80 | 1185 |
| 81 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1189 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 81 | 1189 |
| 81 | {"message": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 1189 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 81 | 1189 | |
| 82 | { "message": "YES, I found bad smells", "bad smells are": ["Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean visitObjectReference(final Pointer objRef, boolean compressed) { return visitObjectReferenceInline(objRef, 0, compressed); } |
feature envy | feature envy | t | t | t | 0 | 1195 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.core.genscavenge/src/com/oracle/svm/core/genscavenge/GreyToBlackObjRefVisitor.java/#L61-L64 | 2 | 82 | 1195 | ||
| 82 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean visitObjectReference(final Pointer objRef, boolean compressed) { return visitObjectReferenceInline(objRef, 0, compressed); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1195 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.core.genscavenge/src/com/oracle/svm/core/genscavenge/GreyToBlackObjRefVisitor.java/#L61-L64 | 1 | 82 | 1195 |
| 83 | { "message": "YES I found bad smells", "bad smells": "1. Long method, 2. Feature envy" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface CompilationIdentifier { enum Verbosity { /** * Only the unique identifier of the compilation. */ ID, /** * Only the name of the compilation unit. */ NAME, /** * {@link #ID} + a readable description. */ DETAILED } CompilationRequestIdentifier INVALID_COMPILATION_ID = new CompilationRequestIdentifier() { @Override public String toString() { return toString(Verbosity.DETAILED); } @Override public String toString(Verbosity verbosity) { return "InvalidCompilationID"; } @Override public CompilationRequest getRequest() { return null; } }; /** * This method is a shortcut for {@link #toString(Verbosity)} with {@link Verbosity#DETAILED}. */ @Override String toString(); /** * Creates a String representation for this compilation identifier with a given * {@link Verbosity}. */ String toString(Verbosity verbosity); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1197 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.core.common/src/org/graalvm/compiler/core/common/CompilationIdentifier.java/#L33-L80 | 2 | 83 | 1197 |
| 83 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface CompilationIdentifier { enum Verbosity { /** * Only the unique identifier of the compilation. */ ID, /** * Only the name of the compilation unit. */ NAME, /** * {@link #ID} + a readable description. */ DETAILED } CompilationRequestIdentifier INVALID_COMPILATION_ID = new CompilationRequestIdentifier() { @Override public String toString() { return toString(Verbosity.DETAILED); } @Override public String toString(Verbosity verbosity) { return "InvalidCompilationID"; } @Override public CompilationRequest getRequest() { return null; } }; /** * This method is a shortcut for {@link #toString(Verbosity)} with {@link Verbosity#DETAILED}. */ @Override String toString(); /** * Creates a String representation for this compilation identifier with a given * {@link Verbosity}. */ String toString(Verbosity verbosity); } |
data class | data class, long method | t | t | t | long method | 0 | 1197 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.core.common/src/org/graalvm/compiler/core/common/CompilationIdentifier.java/#L33-L80 | 1 | 83 | 1197 | |
| 85 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Step deleteJobAsync( String name, String namespace, V1DeleteOptions deleteOptions, ResponseStep responseStep) { return createRequestAsync( responseStep, new RequestParams("deleteJob", namespace, name, deleteOptions), DELETE_JOB); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1212 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L991-L998 | 1 | 85 | 1212 |
| 85 | { "response": "YES I found bad smells the bad smells are: 1.Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Step deleteJobAsync( String name, String namespace, V1DeleteOptions deleteOptions, ResponseStep responseStep) { return createRequestAsync( responseStep, new RequestParams("deleteJob", namespace, name, deleteOptions), DELETE_JOB); } |
feature envy | Not specified | f | f | f | false | 0 | 1212 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L991-L998 | 2 | 85 | 1212 | |
| 86 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 1216 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 1 | 86 | 1216 | |
| 86 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | long method | t | t | t | 0 | 1216 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 2 | 86 | 1216 | ||
| 88 | { "answer": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1229 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 2 | 88 | 1229 |
| 90 | {"message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class TestConfiguration { private String downloadUrl; private final String description; private TestSuite suite; public TestConfiguration(String description) { this.description = description; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getDescription() { return description; } @Override public String toString() { return getClass().getSimpleName() + " [" + description + "]"; } public TestSuite createSuite(TestSuite parentSuite) { suite = new TestSuite("Testing on " + getDescription()); parentSuite.addTest(suite); suite.addTest(new Activation("TestSuite: " + getDescription(), true)); return suite; } public void add(Class clazz) { Assert.isNotNull(suite, "Invoke createSuite() first"); suite.addTestSuite(clazz); } public void done() { Assert.isNotNull(suite, "Invoke createSuite() first"); suite.addTest(new Activation("done", false)); suite = null; } private final class Activation extends TestCase { private final boolean activate; private Activation(String name, boolean activate) { super(name); this.activate = activate; } @Override protected void runTest() throws Throwable { if (activate) { activate(); } else { getDefault().activate(); } } } protected abstract TestConfiguration getDefault(); public abstract void activate(); public abstract TestHarness createHarness(); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1240 | https://github.com/spring-projects/eclipse-integration-tcserver/blob/5b381256cb35cfe2aa21f5093558f7ca927c289f/com.vmware.vfabric.ide.eclipse.tcserver.tests/src/com/vmware/vfabric/ide/eclipse/tcserver/tests/support/TestConfiguration.java/#L21-L95 | 2 | 90 | 1240 |
| 93 | { "response": "YES I found bad smells", "bad smells are": "1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1252 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 2 | 93 | 1252 |
| 94 | {"response": "YES I found bad smells", "the bad smells are": [ "Long method", "Magic strings" ]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ServletConstants { String PAGE_HEADER = "\n" + "\n" + "\n" + " \n" + " Weblogic Monitoring Exporter\n" + "\n" + ""; // The locations of the servlets relative to the web app String MAIN_PAGE = ""; String METRICS_PAGE = "metrics"; String CONFIGURATION_PAGE = "configure"; /** The header used by a web client to send its authentication credentials. **/ String AUTHENTICATION_HEADER = "Authorization"; /** The header used by a web client to send cookies as part of a request. */ String COOKIE_HEADER = "Cookie"; // The field which defines the configuration update action String EFFECT_OPTION = "effect"; // The possible values for the effect String DEFAULT_ACTION = ServletConstants.REPLACE_ACTION; String REPLACE_ACTION = "replace"; String APPEND_ACTION = "append"; } |
data class | long method, magic strings | t | t | f | long method, magic strings | data class | 0 | 1261 | https://github.com/oracle/weblogic-monitoring-exporter/blob/05f1d3c4cc797577801df0ceceb9d92fc31718e8/src/main/java/io/prometheus/wls/rest/ServletConstants.java/#L13-L41 | 2 | 94 | 1261 |
| 97 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1279 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 97 | 1279 |
| 98 | { "answer": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _BuildWebServiceSoap_UpdateBuildDefinitions implements ElementSerializable { // No attributes // Elements protected _BuildDefinition[] updates; public _BuildWebServiceSoap_UpdateBuildDefinitions() { super(); } public _BuildWebServiceSoap_UpdateBuildDefinitions(final _BuildDefinition[] updates) { // TODO : Call super() instead of setting all fields directly? setUpdates(updates); } public _BuildDefinition[] getUpdates() { return this.updates; } public void setUpdates(_BuildDefinition[] value) { this.updates = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.updates != null) { /* * The element type is an array. */ writer.writeStartElement("updates"); for (int iterator0 = 0; iterator0 < this.updates.length; iterator0++) { this.updates[iterator0].writeAsElement( writer, "BuildDefinition"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class, long method | t | t | t | long method | 0 | 1293 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_BuildWebServiceSoap_UpdateBuildDefinitions.java/#L45-L101 | 1 | 98 | 1293 | |
| 98 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _BuildWebServiceSoap_UpdateBuildDefinitions implements ElementSerializable { // No attributes // Elements protected _BuildDefinition[] updates; public _BuildWebServiceSoap_UpdateBuildDefinitions() { super(); } public _BuildWebServiceSoap_UpdateBuildDefinitions(final _BuildDefinition[] updates) { // TODO : Call super() instead of setting all fields directly? setUpdates(updates); } public _BuildDefinition[] getUpdates() { return this.updates; } public void setUpdates(_BuildDefinition[] value) { this.updates = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.updates != null) { /* * The element type is an array. */ writer.writeStartElement("updates"); for (int iterator0 = 0; iterator0 < this.updates.length; iterator0++) { this.updates[iterator0].writeAsElement( writer, "BuildDefinition"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1293 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_BuildWebServiceSoap_UpdateBuildDefinitions.java/#L45-L101 | 2 | 98 | 1293 |
| 99 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | long method | t | t | t | 0 | 1298 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 99 | 1298 | ||
| 99 | {"message":"YES I found bad smells","bad smells are":["1.Long method","2.Complex method","3.Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | 1.long method, 2.complex method, 3.feature envy | t | t | t | 2.complex method, 3.feature envy | 0 | 1298 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 99 | 1298 | |
| 100 | { "output": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: 1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | the bad smells are: 1. long method | t | t | f | the bad smells are: 1. long method | data class | 0 | 1304 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 1 | 100 | 1304 |
| 100 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1304 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 2 | 100 | 1304 |
| 101 | {"message": "YES I found bad smells the bad smells are:", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class CountPageable implements Pageable { private Pageable delegate; public CountPageable(Pageable delegate) { this.delegate = delegate; } public int getPageNumber() { return delegate.getPageNumber(); } public int getPageSize() { return delegate.getPageSize(); } public long getOffset() { return delegate.getOffset(); } public Sort getSort() { // Sorting is not allowed on aggregate count queries. return Sort.unsorted(); } public Pageable next() { return delegate.next(); } public Pageable previousOrFirst() { return delegate.previousOrFirst(); } public Pageable first() { return delegate.first(); } public boolean hasPrevious() { return delegate.hasPrevious(); } } |
data class | data class | t | t | t | 0 | 1307 | https://github.com/spring-projects/spring-data-couchbase/blob/2f4500e9c76541bbbd6a612f7b9283d2455a2dc6/src/main/java/org/springframework/data/couchbase/repository/query/N1qlCountQueryCreator.java/#L83-L124 | 1 | 101 | 1307 | ||
| 101 | { "response": "YES I found bad smells", "bad smells are": [ "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class CountPageable implements Pageable { private Pageable delegate; public CountPageable(Pageable delegate) { this.delegate = delegate; } public int getPageNumber() { return delegate.getPageNumber(); } public int getPageSize() { return delegate.getPageSize(); } public long getOffset() { return delegate.getOffset(); } public Sort getSort() { // Sorting is not allowed on aggregate count queries. return Sort.unsorted(); } public Pageable next() { return delegate.next(); } public Pageable previousOrFirst() { return delegate.previousOrFirst(); } public Pageable first() { return delegate.first(); } public boolean hasPrevious() { return delegate.hasPrevious(); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 1307 | https://github.com/spring-projects/spring-data-couchbase/blob/2f4500e9c76541bbbd6a612f7b9283d2455a2dc6/src/main/java/org/springframework/data/couchbase/repository/query/N1qlCountQueryCreator.java/#L83-L124 | 2 | 101 | 1307 |
| 102 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | data class | t | t | t | 0 | 1315 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 102 | 1315 | ||
| 102 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1315 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 2 | 102 | 1315 |
| 103 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1357 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 2 | 103 | 1357 |
| 103 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | data class, long method | t | t | t | long method | 0 | 1357 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 1 | 103 | 1357 | |
| 105 | { "response": "YES I found bad smells", "detected_bad_smells": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 1384 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 1 | 105 | 1384 | ||
| 105 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1384 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 2 | 105 | 1384 |
| 107 | { "response": "YES I found bad smells", "bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Customer583Repository extends CrudRepository { List findByLastName(String lastName); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1412 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/repo/Customer583Repository.java/#L9-L12 | 2 | 107 | 1412 |
| 108 | { "answer": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 1440 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 1 | 108 | 1440 | ||
| 108 | {"response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1440 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 2 | 108 | 1440 |
| 109 | {"output": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | data class | t | t | t | 0 | 1442 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 109 | 1442 | ||
| 109 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1442 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 109 | 1442 |
| 110 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class PushCommand extends KeyCommand { private List values; private boolean upsert; private Direction direction; private PushCommand(@Nullable ByteBuffer key, List values, Direction direction, boolean upsert) { super(key); this.values = values; this.upsert = upsert; this.direction = direction; } /** * Creates a new {@link PushCommand} for right push ({@literal RPUSH}). * * @return a new {@link PushCommand} for right push ({@literal RPUSH}). */ public static PushCommand right() { return new PushCommand(null, Collections.emptyList(), Direction.RIGHT, true); } /** * Creates a new {@link PushCommand} for left push ({@literal LPUSH}). * * @return a new {@link PushCommand} for left push ({@literal LPUSH}). */ public static PushCommand left() { return new PushCommand(null, Collections.emptyList(), Direction.LEFT, true); } /** * Applies the {@literal value}. Constructs a new command instance with all previously configured properties. * * @param value must not be {@literal null}. * @return a new {@link PushCommand} with {@literal value} applied. */ public PushCommand value(ByteBuffer value) { Assert.notNull(value, "Value must not be null!"); return new PushCommand(null, Collections.singletonList(value), direction, upsert); } /** * Applies a {@link List} of {@literal values}. * * @param values must not be {@literal null}. * @return a new {@link PushCommand} with {@literal values} applied. */ public PushCommand values(List values) { Assert.notNull(values, "Values must not be null!"); return new PushCommand(null, new ArrayList<>(values), direction, upsert); } /** * Applies the {@literal key}. Constructs a new command instance with all previously configured properties. * * @param key must not be {@literal null}. * @return a new {@link PushCommand} with {@literal key} applied. */ public PushCommand to(ByteBuffer key) { Assert.notNull(key, "Key must not be null!"); return new PushCommand(key, values, direction, upsert); } /** * Disable upsert. Constructs a new command instance with all previously configured properties. * * @return a new {@link PushCommand} with upsert disabled. */ public PushCommand ifExists() { return new PushCommand(getKey(), values, direction, false); } /** * @return never {@literal null}. */ public List getValues() { return values; } /** * @return */ public boolean getUpsert() { return upsert; } /** * @return never {@literal null}. */ public Direction getDirection() { return direction; } } |
data class | data class | t | t | t | 0 | 1459 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/ReactiveListCommands.java/#L63-L164 | 1 | 110 | 1459 | ||
| 110 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class PushCommand extends KeyCommand { private List values; private boolean upsert; private Direction direction; private PushCommand(@Nullable ByteBuffer key, List values, Direction direction, boolean upsert) { super(key); this.values = values; this.upsert = upsert; this.direction = direction; } /** * Creates a new {@link PushCommand} for right push ({@literal RPUSH}). * * @return a new {@link PushCommand} for right push ({@literal RPUSH}). */ public static PushCommand right() { return new PushCommand(null, Collections.emptyList(), Direction.RIGHT, true); } /** * Creates a new {@link PushCommand} for left push ({@literal LPUSH}). * * @return a new {@link PushCommand} for left push ({@literal LPUSH}). */ public static PushCommand left() { return new PushCommand(null, Collections.emptyList(), Direction.LEFT, true); } /** * Applies the {@literal value}. Constructs a new command instance with all previously configured properties. * * @param value must not be {@literal null}. * @return a new {@link PushCommand} with {@literal value} applied. */ public PushCommand value(ByteBuffer value) { Assert.notNull(value, "Value must not be null!"); return new PushCommand(null, Collections.singletonList(value), direction, upsert); } /** * Applies a {@link List} of {@literal values}. * * @param values must not be {@literal null}. * @return a new {@link PushCommand} with {@literal values} applied. */ public PushCommand values(List values) { Assert.notNull(values, "Values must not be null!"); return new PushCommand(null, new ArrayList<>(values), direction, upsert); } /** * Applies the {@literal key}. Constructs a new command instance with all previously configured properties. * * @param key must not be {@literal null}. * @return a new {@link PushCommand} with {@literal key} applied. */ public PushCommand to(ByteBuffer key) { Assert.notNull(key, "Key must not be null!"); return new PushCommand(key, values, direction, upsert); } /** * Disable upsert. Constructs a new command instance with all previously configured properties. * * @return a new {@link PushCommand} with upsert disabled. */ public PushCommand ifExists() { return new PushCommand(getKey(), values, direction, false); } /** * @return never {@literal null}. */ public List getValues() { return values; } /** * @return */ public boolean getUpsert() { return upsert; } /** * @return never {@literal null}. */ public Direction getDirection() { return direction; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1459 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/ReactiveListCommands.java/#L63-L164 | 2 | 110 | 1459 |
| 111 | { "message": "YES I found bad smells", "detected_bad_smells": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | data class | t | t | t | 0 | 1461 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 1 | 111 | 1461 | ||
| 111 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1461 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 2 | 111 | 1461 |
| 113 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value @Wither(AccessLevel.PACKAGE) class CollectionJson { private String version; private @Nullable String href; private @JsonInclude(Include.NON_EMPTY) Links links; private @JsonInclude(Include.NON_EMPTY) List> items; private @JsonInclude(Include.NON_EMPTY) List queries; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonTemplate template; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonError error; @JsonCreator CollectionJson(@JsonProperty("version") String version, // @JsonProperty("href") @Nullable String href, // @JsonProperty("links") @Nullable Links links, // @JsonProperty("items") @Nullable List> items, // @JsonProperty("queries") @Nullable List queries, // @JsonProperty("template") @Nullable CollectionJsonTemplate template, // @JsonProperty("error") @Nullable CollectionJsonError error) { this.version = version; this.href = href; this.links = links == null ? Links.NONE : links; this.items = items == null ? Collections.emptyList() : items; this.queries = queries == null ? Collections.emptyList() : queries; this.template = template; this.error = error; } CollectionJson() { this("1.0", null, Links.NONE, Collections.emptyList(), null, null, null); } @SafeVarargs final CollectionJson withItems(CollectionJsonItem... items) { return withItems(Arrays.asList(items)); } CollectionJson withItems(List> items) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withLinks(Link... links) { return withLinks(Links.of(links)); } CollectionJson withLinks(Links links) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withOwnSelfLink() { String href = this.href; if (href == null) { return this; } return withLinks(Links.of(new Link(href)).merge(MergeMode.SKIP_BY_REL, links)); } boolean hasItems() { return !items.isEmpty(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1473 | https://github.com/spring-projects/spring-hateoas/blob/0e02d4f04117e03ab94110c9de09b2ac28d55599/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java/#L41-L107 | 2 | 113 | 1473 |
| 113 | {"response": "YES I found bad smells", "identified_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Value @Wither(AccessLevel.PACKAGE) class CollectionJson { private String version; private @Nullable String href; private @JsonInclude(Include.NON_EMPTY) Links links; private @JsonInclude(Include.NON_EMPTY) List> items; private @JsonInclude(Include.NON_EMPTY) List queries; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonTemplate template; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonError error; @JsonCreator CollectionJson(@JsonProperty("version") String version, // @JsonProperty("href") @Nullable String href, // @JsonProperty("links") @Nullable Links links, // @JsonProperty("items") @Nullable List> items, // @JsonProperty("queries") @Nullable List queries, // @JsonProperty("template") @Nullable CollectionJsonTemplate template, // @JsonProperty("error") @Nullable CollectionJsonError error) { this.version = version; this.href = href; this.links = links == null ? Links.NONE : links; this.items = items == null ? Collections.emptyList() : items; this.queries = queries == null ? Collections.emptyList() : queries; this.template = template; this.error = error; } CollectionJson() { this("1.0", null, Links.NONE, Collections.emptyList(), null, null, null); } @SafeVarargs final CollectionJson withItems(CollectionJsonItem... items) { return withItems(Arrays.asList(items)); } CollectionJson withItems(List> items) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withLinks(Link... links) { return withLinks(Links.of(links)); } CollectionJson withLinks(Links links) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withOwnSelfLink() { String href = this.href; if (href == null) { return this; } return withLinks(Links.of(new Link(href)).merge(MergeMode.SKIP_BY_REL, links)); } boolean hasItems() { return !items.isEmpty(); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 1473 | https://github.com/spring-projects/spring-hateoas/blob/0e02d4f04117e03ab94110c9de09b2ac28d55599/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java/#L41-L107 | 1 | 113 | 1473 |
| 114 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Magic number" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | long method, magic number | t | t | f | long method, magic number | data class | 0 | 1489 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 114 | 1489 |
| 114 | { "response": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | long method | t | t | f | long method | data class | 0 | 1489 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 114 | 1489 |
| 116 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BeanRegistration { private final Class annotatedClass; @Nullable private final Supplier supplier; private final Class[] qualifiers; public BeanRegistration( Class annotatedClass, @Nullable Supplier supplier, Class[] qualifiers) { this.annotatedClass = annotatedClass; this.supplier = supplier; this.qualifiers = qualifiers; } public Class getAnnotatedClass() { return this.annotatedClass; } @Nullable @SuppressWarnings("rawtypes") public Supplier getSupplier() { return this.supplier; } public Class[] getQualifiers() { return this.qualifiers; } @Override public String toString() { return this.annotatedClass.getName(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1503 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContext.java/#L342-L376 | 2 | 116 | 1503 |
| 116 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BeanRegistration { private final Class annotatedClass; @Nullable private final Supplier supplier; private final Class[] qualifiers; public BeanRegistration( Class annotatedClass, @Nullable Supplier supplier, Class[] qualifiers) { this.annotatedClass = annotatedClass; this.supplier = supplier; this.qualifiers = qualifiers; } public Class getAnnotatedClass() { return this.annotatedClass; } @Nullable @SuppressWarnings("rawtypes") public Supplier getSupplier() { return this.supplier; } public Class[] getQualifiers() { return this.qualifiers; } @Override public String toString() { return this.annotatedClass.getName(); } } |
data class | data class | t | t | t | 0 | 1503 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContext.java/#L342-L376 | 1 | 116 | 1503 | ||
| 117 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1507 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 2 | 117 | 1507 |
| 118 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @NonNull public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 1509 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java/#L426-L430 | 1 | 118 | 1509 |
| 118 | { "response": "YES I found bad smells", "detected_code_smells": { "the_bad_smells_are": [ "Long method", "Feature envy" ] } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @NonNull public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; } |
feature envy | the_bad_smells_are: long method, feature envy | t | t | t | the_bad_smells_are: long method | 0 | 1509 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java/#L426-L430 | 2 | 118 | 1509 | |
| 119 | { "message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 1514 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 119 | 1514 | |
| 119 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | 1. long method | t | t | t | 0 | 1514 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 119 | 1514 | ||
| 120 | {"message": "YES I found bad smells the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1519 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 2 | 120 | 1519 |
| 120 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | data class | t | t | t | 0 | 1519 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 1 | 120 | 1519 | ||
| 121 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void formatElement(IProgressMonitor monitor) { FormatProcessorXML formatProcessor = new FormatProcessorXML(); formatProcessor.setProgressMonitor(monitor); formatProcessor.getFormatPreferences().setClearAllBlankLines(true); formatProcessor.formatModel(model); CleanupProcessorXML bla = new CleanupProcessorXML(); bla.getCleanupPreferences().setCompressEmptyElementTags(true); bla.cleanupModel(model); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1534 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.webflow.ui.graph/src/org/springframework/ide/eclipse/webflow/ui/graph/WebflowEditor.java/#L578-L587 | 2 | 121 | 1534 | |
| 122 | {"output": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Data static class VaultInitializationResponseImpl implements VaultInitializationResponse { private List keys = new ArrayList<>(); @JsonProperty("root_token") private String rootToken = ""; public VaultToken getRootToken() { return VaultToken.of(rootToken); } } |
data class | Not specified | f | f | f | false | 0 | 1535 | https://github.com/spring-projects/spring-vault/blob/6e36eb10b02c6931c3b565c5d9d76f5e217bf309/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java/#L414-L425 | 2 | 122 | 1535 | |
| 122 | {"response": "YES I found bad smells", "bad smells are:": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Data static class VaultInitializationResponseImpl implements VaultInitializationResponse { private List keys = new ArrayList<>(); @JsonProperty("root_token") private String rootToken = ""; public VaultToken getRootToken() { return VaultToken.of(rootToken); } } |
data class | data class | t | t | t | 0 | 1535 | https://github.com/spring-projects/spring-vault/blob/6e36eb10b02c6931c3b565c5d9d76f5e217bf309/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java/#L414-L425 | 1 | 122 | 1535 | ||
| 123 | {"message": "YES I found bad smells, the bad smells are: 1. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public QMUIAlphaImageButton addRightImageButton(int drawableResId, int viewId) { return mTopBar.addRightImageButton(drawableResId, viewId); } |
feature envy | 1. feature envy | t | t | t | 0 | 1542 | https://github.com/Tencent/QMUI_Android/blob/6ff5493a05845918c126cce8a3e639f8d996481b/qmui/src/main/java/com/qmuiteam/qmui/widget/QMUITopBarLayout.java/#L136-L138 | 1 | 123 | 1542 | ||
| 123 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public QMUIAlphaImageButton addRightImageButton(int drawableResId, int viewId) { return mTopBar.addRightImageButton(drawableResId, viewId); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1542 | https://github.com/Tencent/QMUI_Android/blob/6ff5493a05845918c126cce8a3e639f8d996481b/qmui/src/main/java/com/qmuiteam/qmui/widget/QMUITopBarLayout.java/#L136-L138 | 2 | 123 | 1542 | |
| 124 | {"answer": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface PropertyPathPart extends EObject { /** * Returns the value of the 'Name' attribute. * * * If the meaning of the 'Name' attribute isn't clear, * there really should be more of a description here... * * * @return the value of the 'Name' attribute. * @see #setName(String) * @see org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.Bug332217TestLanguagePackage#getPropertyPathPart_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.PropertyPathPart#getName Name}' attribute. * * * @param value the new value of the 'Name' attribute. * @see #getName() * @generated */ void setName(String value); } // PropertyPathPart |
data class | 'Data Class' | t | t | f | {',D,a,t,a," ",C,l,a,s,s,'} | {',D,t," ",C,'} | 0 | 1552 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/bug332217TestLanguage/PropertyPathPart.java/#L24-L52 | 1 | 124 | 1552 |
| 124 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface PropertyPathPart extends EObject { /** * Returns the value of the 'Name' attribute. * * * If the meaning of the 'Name' attribute isn't clear, * there really should be more of a description here... * * * @return the value of the 'Name' attribute. * @see #setName(String) * @see org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.Bug332217TestLanguagePackage#getPropertyPathPart_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.PropertyPathPart#getName Name}' attribute. * * * @param value the new value of the 'Name' attribute. * @see #getName() * @generated */ void setName(String value); } // PropertyPathPart |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1552 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/bug332217TestLanguage/PropertyPathPart.java/#L24-L52 | 2 | 124 | 1552 |
| 125 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | data class | t | t | t | 0 | 1573 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 125 | 1573 | ||
| 125 | { "response": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1573 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 125 | 1573 |
| 127 | {"message": "YES I found bad smells. The bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | 1. data class | t | t | t | 0 | 1581 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 1 | 127 | 1581 | ||
| 127 | { "output": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1581 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 2 | 127 | 1581 |
| 130 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ParseSpec withTimestampSpec(TimestampSpec spec) { return new TimeAndDimsParseSpec(spec, getDimensionsSpec()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1610 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/data/input/impl/TimeAndDimsParseSpec.java/#L70-L74 | 2 | 130 | 1610 | |
| 130 | { "response": "YES I found bad smells", "bad smells are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ParseSpec withTimestampSpec(TimestampSpec spec) { return new TimeAndDimsParseSpec(spec, getDimensionsSpec()); } |
feature envy | feature envy | t | t | t | 0 | 1610 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/data/input/impl/TimeAndDimsParseSpec.java/#L70-L74 | 1 | 130 | 1610 | ||
| 131 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Anonymous inner class" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static long gzip(final ByteSource in, final ByteSink out, Predicate shouldRetry) { return StreamUtils.retryCopy( in, new ByteSink() { @Override public OutputStream openStream() throws IOException { return new GZIPOutputStream(out.openStream()); } }, shouldRetry, DEFAULT_RETRY_COUNT ); } |
feature envy | long method, anonymous inner class | t | t | f | long method, anonymous inner class | feature envy | 0 | 1618 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/utils/CompressionUtils.java/#L491-L506 | 2 | 131 | 1618 |
| 131 | { "response": "YES I found bad smells", "detected_bad_smells": "the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static long gzip(final ByteSource in, final ByteSink out, Predicate shouldRetry) { return StreamUtils.retryCopy( in, new ByteSink() { @Override public OutputStream openStream() throws IOException { return new GZIPOutputStream(out.openStream()); } }, shouldRetry, DEFAULT_RETRY_COUNT ); } |
feature envy | the bad smells are: 1. long method | t | t | f | the bad smells are: 1. long method | feature envy | 0 | 1618 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/utils/CompressionUtils.java/#L491-L506 | 1 | 131 | 1618 |
| 133 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnnotPage extends ContactsDisplayPage { @SpringBean private ContactDao dao; @Override protected ContactDataProvider getDataProvider() { return new ProxyDataProvider(dao); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1634 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-examples/src/main/java/org/apache/wicket/examples/spring/annot/web/AnnotPage.java/#L27-L37 | 2 | 133 | 1634 |
| 135 | {"response": "YES, I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1664 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 135 | 1664 |
| 135 | { "response": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1664 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 135 | 1664 |
| 136 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | long method | t | t | t | 0 | 1673 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 1 | 136 | 1673 | ||
| 136 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | long method, duplicate code | t | t | t | duplicate code | 0 | 1673 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 2 | 136 | 1673 | |
| 137 | {"message": "YES I found bad smells", "bad smells are:": "1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1730 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 2 | 137 | 1730 |
| 139 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | data class, long method | t | t | t | long method | 0 | 1751 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 1 | 139 | 1751 | |
| 139 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1751 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 139 | 1751 |
| 140 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | 1. data class | t | t | t | 0 | 1770 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 140 | 1770 | ||
| 140 | {"response": "YES I found bad smells the bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1770 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 140 | 1770 |
| 141 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
long method | long method | t | t | t | 0 | 1773 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 1 | 141 | 1773 | ||
| 141 | { "response": "YES I found bad smells", "details": { "the bad smells are": [ "Long method" ] } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
long method | the bad smells are: long method | t | t | t | 0 | 1773 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 2 | 141 | 1773 | ||
| 142 | { "message": "YES I found bad smells", "bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1777 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 2 | 142 | 1777 |
| 142 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | long method | t | t | f | long method | data class | 0 | 1777 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 1 | 142 | 1777 |
| 143 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | data class, long method | t | t | t | long method | 0 | 1786 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 143 | 1786 | |
| 143 | {"response":"YES I found bad smells", "the bad smells are":[ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1786 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 143 | 1786 |
| 146 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | long method | t | t | f | long method | data class | 0 | 1826 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 1 | 146 | 1826 |
| 146 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1826 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 2 | 146 | 1826 |
| 148 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | data class | t | t | t | 0 | 1844 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 148 | 1844 | ||
| 148 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1844 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 148 | 1844 |
| 151 | {"message": "YES, I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1911 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 151 | 1911 |
| 152 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1930 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 152 | 1930 |
| 152 | { "response": "YES I found bad smells", "bad smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1930 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 2 | 152 | 1930 | |
| 153 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1932 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 1 | 153 | 1932 |
| 153 | { "response": "YES I found bad smells. The bad smells are: 1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | Not specified | f | f | f | false | 0 | 1932 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 2 | 153 | 1932 | |
| 154 | { "answer": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String repeat(String s, int c) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c; i++) sb.append(s); return sb.toString(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1939 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/shell/src/main/java/org/apache/accumulo/shell/Shell.java/#L1075-L1080 | 1 | 154 | 1939 |
| 154 | { "message": "YES I found bad smells", "bad smells": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String repeat(String s, int c) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c; i++) sb.append(s); return sb.toString(); } |
feature envy | long method, duplicate code | t | t | f | long method, duplicate code | feature envy | 0 | 1939 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/shell/src/main/java/org/apache/accumulo/shell/Shell.java/#L1075-L1080 | 2 | 154 | 1939 |
| 155 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1952 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 1 | 155 | 1952 |
| 155 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1952 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 2 | 155 | 1952 |
| 156 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ArgumentProcessor getProcessor( Class< ? extends ArgumentProcessor> processorClass) { ArgumentProcessor processor; try { processor = processorClass.getConstructor().newInstance(); } catch (Exception e) { throw new BuildException("The argument processor class" + processorClass.getName() + " could not be instantiated with a default constructor", e); } return processor; } |
feature envy | f | f | f | feature envy | 0 | 1968 | https://github.com/apache/ant/blob/9722f062dc68d6c321faf751621162ac8444c585/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java/#L121-L133 | 2 | 156 | 1968 | |||
| 156 | {"message": "YES, I found bad smells", "smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ArgumentProcessor getProcessor( Class< ? extends ArgumentProcessor> processorClass) { ArgumentProcessor processor; try { processor = processorClass.getConstructor().newInstance(); } catch (Exception e) { throw new BuildException("The argument processor class" + processorClass.getName() + " could not be instantiated with a default constructor", e); } return processor; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1968 | https://github.com/apache/ant/blob/9722f062dc68d6c321faf751621162ac8444c585/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java/#L121-L133 | 1 | 156 | 1968 |
| 158 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1979 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 1 | 158 | 1979 |
| 158 | {"response": "YES I found bad smells", "bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 1979 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 2 | 158 | 1979 |
| 160 | { "message": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | 1. data class | t | t | t | 0 | 1985 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 1 | 160 | 1985 | ||
| 160 | { "response": "YES I found bad smells. The bad smells are: 1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | Not specified | f | f | f | false | 0 | 1985 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 2 | 160 | 1985 | |
| 161 | {"message": "YES I found bad smells the bad smells are:", "bad_smells": [ "Long method", "Exception handling inconsistency" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | long method, exception handling inconsistency | t | t | f | long method, exception handling inconsistency | feature envy | 0 | 1994 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 2 | 161 | 1994 |
| 161 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 1994 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 1 | 161 | 1994 |
| 167 | {"message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2023 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 2 | 167 | 2023 |
| 169 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 2032 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 2 | 169 | 2032 | ||
| 169 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 2032 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 1 | 169 | 2032 | ||
| 170 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Long parameter list", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | long method, long parameter list, feature envy | t | t | f | long method, long parameter list, feature envy | data class | 0 | 2035 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 170 | 2035 |
| 173 | { "response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | long method, data class | t | t | t | data class | 0 | 2041 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 173 | 2041 | |
| 173 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2041 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 173 | 2041 | |
| 175 | { "answer": "YES I found bad smells", "bad smells are": [ { "name": "Data Class" }, { "name": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | name: data class, name: long method | t | t | t | name: long method | 0 | 2046 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 175 | 2046 | |
| 175 | { "output": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Duplicate code", "3. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | 1. long method, 2. duplicate code, 3. feature envy | t | t | f | 1. long method, 2. duplicate code, 3. feature envy | data class | 0 | 2046 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 175 | 2046 |
| 181 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Data class" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | long method, data class | t | t | t | long method | 0 | 2064 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 181 | 2064 | |
| 181 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2064 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 181 | 2064 |
| 187 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | long method | t | t | f | long method | data class | 0 | 2120 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 1 | 187 | 2120 |
| 187 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long method", "Duplicate code", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | long method, duplicate code, feature envy | t | t | f | long method, duplicate code, feature envy | data class | 0 | 2120 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 2 | 187 | 2120 |
| 190 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 2196 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 190 | 2196 |
| 190 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 2196 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 190 | 2196 | |
| 193 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | f | f | f | data class | 0 | 2220 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 193 | 2220 | |||
| 195 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
long method | 1. long method | t | t | t | 0 | 2234 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 2 | 195 | 2234 | ||
| 195 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
long method | 1. long method | t | t | t | 0 | 2234 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 1 | 195 | 2234 | ||
| 197 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | 1. long method | t | t | t | 0 | 2237 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 197 | 2237 | ||
| 197 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | 1. long method | t | t | t | 0 | 2237 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 197 | 2237 | ||
| 198 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 2238 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 198 | 2238 |
| 198 | {"message": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 2238 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 198 | 2238 | |
| 199 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method | t | t | t | 0 | 2241 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 1 | 199 | 2241 | ||
| 199 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2241 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 2 | 199 | 2241 | |
| 205 | { "response": "YES I found bad smells.", "the bad smells are": ["1. Long method", "2. Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2299 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 2 | 205 | 2299 |
| 209 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProjectList extends DataType implements Cloneable { protected ArrayList list = new ArrayList(); /** * add a project * @param pro */ public void addProjectInfo(ProjectInfo pro) { list.add(pro); } /** * get project by index * @param index * @return */ public ProjectInfo getProject(int index) { assert(index>=0 && index<list.size()); return (ProjectInfo)list.get(index); } /** * get count * @return */ public int getCount() { return list.size(); } } |
data class | data class | t | t | t | 0 | 2311 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/build/org.eclipse.birt.build/src/org/eclipse/birt/build/ProjectList.java/#L24-L61 | 1 | 209 | 2311 | ||
| 209 | {"message": "YES I found bad smells the bad smells are: 1.Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProjectList extends DataType implements Cloneable { protected ArrayList list = new ArrayList(); /** * add a project * @param pro */ public void addProjectInfo(ProjectInfo pro) { list.add(pro); } /** * get project by index * @param index * @return */ public ProjectInfo getProject(int index) { assert(index>=0 && index<list.size()); return (ProjectInfo)list.get(index); } /** * get count * @return */ public int getCount() { return list.size(); } } |
data class | 1.long method | t | t | f | 1.long method | data class | 0 | 2311 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/build/org.eclipse.birt.build/src/org/eclipse/birt/build/ProjectList.java/#L24-L61 | 2 | 209 | 2311 |
| 211 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code 4. Primitive obsession 5. Inappropriate intimacy 6. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | Feature envy2 Long method3 Duplicate code4 Primitive obsession5 Inappropriate intimacy6 Shotgun surgery | t | f | f | . Feature envy2. Long method3. Duplicate code4. Primitive obsession5. Inappropriate intimacy6. Shotgun surgery | data class | 0 | 2314 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 2 | 211 | 2314 |
| 213 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2324 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 2 | 213 | 2324 |
| 213 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2324 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 1 | 213 | 2324 |
| 214 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | f | f | f | data class | 0 | 2325 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 2 | 214 | 2325 | |||
| 214 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2325 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 1 | 214 | 2325 |
| 216 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | long method | t | t | t | 0 | 2343 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 216 | 2343 | ||
| 216 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2343 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 216 | 2343 | |
| 217 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | data class | t | t | t | 0 | 2368 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 1 | 217 | 2368 | ||
| 217 | {"message": "YES I found bad smells the bad smells are: 1.Long method, 2.Magic number, 3.Data class"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | 1.long method, 2.magic number, 3.data class | t | t | t | 1.long method, 2.magic number | 0 | 2368 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 2 | 217 | 2368 | |
| 221 | {"error": "YES I found bad smells", "the bad smells are": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BookKeeper implements org.apache.bookkeeper.client.api.BookKeeper { private static final Logger LOG = LoggerFactory.getLogger(BookKeeper.class); final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; // The stats logger for this client. private final StatsLogger statsLogger; private final BookKeeperClientStats clientStats; // whether the event loop group is one we created, or is owned by whoever // instantiated us boolean ownEventLoopGroup = false; final BookieClient bookieClient; final BookieWatcherImpl bookieWatcher; final OrderedExecutor mainWorkerPool; final OrderedScheduler scheduler; final HashedWheelTimer requestTimer; final boolean ownTimer; final FeatureProvider featureProvider; final ScheduledExecutorService bookieInfoScheduler; final MetadataClientDriver metadataDriver; // Ledger manager responsible for how to store ledger meta data final LedgerManagerFactory ledgerManagerFactory; final LedgerManager ledgerManager; final LedgerIdGenerator ledgerIdGenerator; // Ensemble Placement Policy final EnsemblePlacementPolicy placementPolicy; BookieInfoReader bookieInfoReader; final ClientConfiguration conf; final ClientInternalConf internalConf; // Close State boolean closed = false; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); /** * BookKeeper Client Builder to build client instances. * * @see BookKeeperBuilder */ public static class Builder { final ClientConfiguration conf; ZooKeeper zk = null; EventLoopGroup eventLoopGroup = null; ByteBufAllocator allocator = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; DNSToSwitchMapping dnsResolver = null; HashedWheelTimer requestTimer = null; FeatureProvider featureProvider = null; Builder(ClientConfiguration conf) { this.conf = conf; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #eventLoopGroup(EventLoopGroup)} * @see #eventLoopGroup(EventLoopGroup) */ @Deprecated public Builder setEventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #zk(ZooKeeper)} * @see #zk(ZooKeeper) */ @Deprecated public Builder setZookeeper(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @deprecated since 4.5, use {@link #statsLogger(StatsLogger)} * @see #statsLogger(StatsLogger) */ @Deprecated public Builder setStatsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @since 4.5 */ public Builder eventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ByteBufAllocator}. * * @param allocator an external {@link ByteBufAllocator} to use by the bookkeeper client. * @return client builder. * @since 4.9 */ public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @since 4.5 */ @Deprecated public Builder zk(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @since 4.5 */ public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client to use the provided dns resolver {@link DNSToSwitchMapping}. * * @param dnsResolver dns resolver for placement policy to use for resolving network locations. * @return client builder * @since 4.5 */ public Builder dnsResolver(DNSToSwitchMapping dnsResolver) { this.dnsResolver = dnsResolver; return this; } /** * Configure the bookkeeper client to use a provided {@link HashedWheelTimer}. * * @param requestTimer request timer for client to manage timer related tasks. * @return client builder * @since 4.5 */ public Builder requestTimer(HashedWheelTimer requestTimer) { this.requestTimer = requestTimer; return this; } /** * Feature Provider. * * @param featureProvider * @return */ public Builder featureProvider(FeatureProvider featureProvider) { this.featureProvider = featureProvider; return this; } public BookKeeper build() throws IOException, InterruptedException, BKException { checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, allocator, statsLogger, dnsResolver, requestTimer, featureProvider); } } public static Builder forConfig(final ClientConfiguration conf) { return new Builder(conf); } /** * Create a bookkeeper client. A zookeeper client and a client event loop group * will be instantiated as part of this constructor. * * @param servers * A list of one of more servers on which zookeeper is running. The * client assumes that the running bookies have been registered with * zookeeper under the path * {@link AbstractConfiguration#getZkAvailableBookiesPath()} * @throws IOException * @throws InterruptedException */ public BookKeeper(String servers) throws IOException, InterruptedException, BKException { this(new ClientConfiguration().setMetadataServiceUri("zk+null://" + servers + "/ledgers")); } /** * Create a bookkeeper client using a configuration object. * A zookeeper client and a client event loop group will be * instantiated as part of this constructor. * * @param conf * Client Configuration object * @throws IOException * @throws InterruptedException */ public BookKeeper(final ClientConfiguration conf) throws IOException, InterruptedException, BKException { this(conf, null, null, null, NullStatsLogger.INSTANCE, null, null, null); } private static ZooKeeper validateZooKeeper(ZooKeeper zk) throws NullPointerException, IOException { checkNotNull(zk, "No zookeeper instance provided"); if (!zk.getState().isConnected()) { LOG.error("Unconnected zookeeper handle passed to bookkeeper"); throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); } return zk; } private static EventLoopGroup validateEventLoopGroup(EventLoopGroup eventLoopGroup) throws NullPointerException { checkNotNull(eventLoopGroup, "No Event Loop Group provided"); return eventLoopGroup; } /** * Create a bookkeeper client but use the passed in zookeeper client instead * of instantiating one. * * @param conf * Client Configuration object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered * @throws IOException * @throws InterruptedException */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), null, null, NullStatsLogger.INSTANCE, null, null, null); } /** * Create a bookkeeper client but use the passed in zookeeper client and * client event loop group instead of instantiating those. * * @param conf * Client Configuration Object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered. The ZooKeeper client must be connected * before it is passed to BookKeeper. Otherwise a KeeperException is thrown. * @param eventLoopGroup * An event loop group that will be used to create connections to the bookies * @throws IOException * @throws InterruptedException * @throws BKException in the event of a bookkeeper connection error */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk, EventLoopGroup eventLoopGroup) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), validateEventLoopGroup(eventLoopGroup), null, NullStatsLogger.INSTANCE, null, null, null); } /** * Constructor for use with the builder. Other constructors also use it. */ @SuppressWarnings("deprecation") @VisibleForTesting BookKeeper(ClientConfiguration conf, ZooKeeper zkc, EventLoopGroup eventLoopGroup, ByteBufAllocator byteBufAllocator, StatsLogger rootStatsLogger, DNSToSwitchMapping dnsResolver, HashedWheelTimer requestTimer, FeatureProvider featureProvider) throws IOException, InterruptedException, BKException { this.conf = conf; // initialize feature provider if (null == featureProvider) { this.featureProvider = SettableFeatureProvider.DISABLE_ALL; } else { this.featureProvider = featureProvider; } this.internalConf = ClientInternalConf.fromConfigAndFeatureProvider(conf, this.featureProvider); // initialize resources this.scheduler = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("BookKeeperClientScheduler").build(); this.mainWorkerPool = OrderedExecutor.newBuilder() .name("BookKeeperClientWorker") .numThreads(conf.getNumWorkerThreads()) .statsLogger(rootStatsLogger) .traceTaskExecution(conf.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(conf.getPreserveMdcForTaskExecution()) .traceTaskWarnTimeMicroSec(conf.getTaskExecutionWarnTimeMicros()) .enableBusyWait(conf.isBusyWaitEnabled()) .build(); // initialize stats logger this.statsLogger = rootStatsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE); this.clientStats = BookKeeperClientStats.newInstance(this.statsLogger); // initialize metadata driver try { String metadataServiceUriStr = conf.getMetadataServiceUri(); if (null != metadataServiceUriStr) { this.metadataDriver = MetadataDrivers.getClientDriver(URI.create(metadataServiceUriStr)); } else { checkNotNull(zkc, "No external zookeeper provided when no metadata service uri is found"); this.metadataDriver = MetadataDrivers.getClientDriver("zk"); } this.metadataDriver.initialize( conf, scheduler, rootStatsLogger, java.util.Optional.ofNullable(zkc)); } catch (ConfigurationException ce) { LOG.error("Failed to initialize metadata client driver using invalid metadata service uri", ce); throw new IOException("Failed to initialize metadata client driver", ce); } catch (MetadataException me) { LOG.error("Encountered metadata exceptions on initializing metadata client driver", me); throw new IOException("Failed to initialize metadata client driver", me); } // initialize event loop group if (null == eventLoopGroup) { this.eventLoopGroup = EventLoopUtil.getClientEventLoopGroup(conf, new DefaultThreadFactory("bookkeeper-io")); this.ownEventLoopGroup = true; } else { this.eventLoopGroup = eventLoopGroup; this.ownEventLoopGroup = false; } if (byteBufAllocator != null) { this.allocator = byteBufAllocator; } else { this.allocator = ByteBufAllocatorBuilder.create() .poolingPolicy(conf.getAllocatorPoolingPolicy()) .poolingConcurrency(conf.getAllocatorPoolingConcurrency()) .outOfMemoryPolicy(conf.getAllocatorOutOfMemoryPolicy()) .leakDetectionPolicy(conf.getAllocatorLeakDetectionPolicy()) .build(); } // initialize bookie client this.bookieClient = new BookieClientImpl(conf, this.eventLoopGroup, this.allocator, this.mainWorkerPool, scheduler, rootStatsLogger); if (null == requestTimer) { this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieClientTimer-%d").build(), conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS, conf.getTimeoutTimerNumTicks()); this.ownTimer = true; } else { this.requestTimer = requestTimer; this.ownTimer = false; } // initialize the ensemble placement this.placementPolicy = initializeEnsemblePlacementPolicy(conf, dnsResolver, this.requestTimer, this.featureProvider, this.statsLogger); this.bookieWatcher = new BookieWatcherImpl( conf, this.placementPolicy, metadataDriver.getRegistrationClient(), this.statsLogger.scope(WATCHER_SCOPE)); if (conf.getDiskWeightBasedPlacementEnabled()) { LOG.info("Weighted ledger placement enabled"); ThreadFactoryBuilder tFBuilder = new ThreadFactoryBuilder() .setNameFormat("BKClientMetaDataPollScheduler-%d"); this.bookieInfoScheduler = Executors.newSingleThreadScheduledExecutor(tFBuilder.build()); this.bookieInfoReader = new BookieInfoReader(this, conf, this.bookieInfoScheduler); this.bookieWatcher.initialBlockingBookieRead(); this.bookieInfoReader.start(); } else { LOG.info("Weighted ledger placement is not enabled"); this.bookieInfoScheduler = null; this.bookieInfoReader = new BookieInfoReader(this, conf, null); this.bookieWatcher.initialBlockingBookieRead(); } // initialize ledger manager try { this.ledgerManagerFactory = this.metadataDriver.getLedgerManagerFactory(); } catch (MetadataException e) { throw new IOException("Failed to initialize ledger manager factory", e); } this.ledgerManager = new CleanupLedgerManager(ledgerManagerFactory.newLedgerManager()); this.ledgerIdGenerator = ledgerManagerFactory.newLedgerIdGenerator(); scheduleBookieHealthCheckIfEnabled(conf); } /** * Allow to extend BookKeeper for mocking in unit tests. */ @VisibleForTesting BookKeeper() { conf = new ClientConfiguration(); internalConf = ClientInternalConf.fromConfig(conf); statsLogger = NullStatsLogger.INSTANCE; clientStats = BookKeeperClientStats.newInstance(statsLogger); scheduler = null; requestTimer = null; metadataDriver = null; placementPolicy = null; ownTimer = false; mainWorkerPool = null; ledgerManagerFactory = null; ledgerManager = null; ledgerIdGenerator = null; featureProvider = null; eventLoopGroup = null; bookieWatcher = null; bookieInfoScheduler = null; bookieClient = null; allocator = UnpooledByteBufAllocator.DEFAULT; } private EnsemblePlacementPolicy initializeEnsemblePlacementPolicy(ClientConfiguration conf, DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, FeatureProvider featureProvider, StatsLogger statsLogger) throws IOException { try { Class policyCls = conf.getEnsemblePlacementPolicy(); return ReflectionUtils.newInstance(policyCls).initialize(conf, java.util.Optional.ofNullable(dnsResolver), timer, featureProvider, statsLogger); } catch (ConfigurationException e) { throw new IOException("Failed to initialize ensemble placement policy : ", e); } } int getReturnRc(int rc) { return getReturnRc(bookieClient, rc); } static int getReturnRc(BookieClient bookieClient, int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (bookieClient.isClosed()) { return BKException.Code.ClientClosedException; } else { return rc; } } } void scheduleBookieHealthCheckIfEnabled(ClientConfiguration conf) { if (conf.isBookieHealthCheckEnabled()) { scheduler.scheduleAtFixedRate(new SafeRunnable() { @Override public void safeRun() { checkForFaultyBookies(); } }, conf.getBookieHealthCheckIntervalSeconds(), conf.getBookieHealthCheckIntervalSeconds(), TimeUnit.SECONDS); } } void checkForFaultyBookies() { List faultyBookies = bookieClient.getFaultyBookies(); for (BookieSocketAddress faultyBookie : faultyBookies) { bookieWatcher.quarantineBookie(faultyBookie); } } /** * Returns ref to speculative read counter, needed in PendingReadOp. */ @VisibleForTesting public LedgerManager getLedgerManager() { return ledgerManager; } @VisibleForTesting LedgerManager getUnderlyingLedgerManager() { return ((CleanupLedgerManager) ledgerManager).getUnderlying(); } @VisibleForTesting LedgerIdGenerator getLedgerIdGenerator() { return ledgerIdGenerator; } @VisibleForTesting ReentrantReadWriteLock getCloseLock() { return closeLock; } @VisibleForTesting boolean isClosed() { return closed; } @VisibleForTesting BookieWatcher getBookieWatcher() { return bookieWatcher; } public OrderedExecutor getMainWorkerPool() { return mainWorkerPool; } @VisibleForTesting OrderedScheduler getScheduler() { return scheduler; } @VisibleForTesting EnsemblePlacementPolicy getPlacementPolicy() { return placementPolicy; } @VisibleForTesting public MetadataClientDriver getMetadataClientDriver() { return metadataDriver; } /** * There are 3 digest types that can be used for verification. The CRC32 is * cheap to compute but does not protect against byzantine bookies (i.e., a * bookie might report fake bytes and a matching CRC32). The MAC code is more * expensive to compute, but is protected by a password, i.e., a bookie can't * report fake bytes with a mathching MAC unless it knows the password. * The CRC32C, which use SSE processor instruction, has better performance than CRC32. * Legacy DigestType for backward compatibility. If we want to add new DigestType, * we should add it in here, client.api.DigestType and DigestType in DataFormats.proto. * If the digest type is set/passed in as DUMMY, a dummy digest is added/checked. * This DUMMY digest is mostly for test purposes or in situations/use-cases * where digest is considered a overhead. */ public enum DigestType { MAC, CRC32, CRC32C, DUMMY; public static DigestType fromApiDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { switch (digestType) { case MAC: return DigestType.MAC; case CRC32: return DigestType.CRC32; case CRC32C: return DigestType.CRC32C; case DUMMY: return DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public static DataFormats.LedgerMetadataFormat.DigestType toProtoDigestType(DigestType digestType) { switch (digestType) { case MAC: return DataFormats.LedgerMetadataFormat.DigestType.HMAC; case CRC32: return DataFormats.LedgerMetadataFormat.DigestType.CRC32; case CRC32C: return DataFormats.LedgerMetadataFormat.DigestType.CRC32C; case DUMMY: return DataFormats.LedgerMetadataFormat.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public org.apache.bookkeeper.client.api.DigestType toApiDigestType() { switch (this) { case MAC: return org.apache.bookkeeper.client.api.DigestType.MAC; case CRC32: return org.apache.bookkeeper.client.api.DigestType.CRC32; case CRC32C: return org.apache.bookkeeper.client.api.DigestType.CRC32C; case DUMMY: return org.apache.bookkeeper.client.api.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + this); } } } ZooKeeper getZkHandle() { return ((ZKMetadataClientDriver) metadataDriver).getZk(); } protected ClientConfiguration getConf() { return conf; } StatsLogger getStatsLogger() { return statsLogger; } /** * Get the BookieClient, currently used for doing bookie recovery. * * @return BookieClient for the BookKeeper instance. */ BookieClient getBookieClient() { return bookieClient; } /** * Retrieves BookieInfo from all the bookies in the cluster. It sends requests * to all the bookies in parallel and returns the info from the bookies that responded. * If there was an error in reading from any bookie, nothing will be returned for * that bookie in the map. * @return map * A map of bookieSocketAddress to its BookiInfo * @throws BKException * @throws InterruptedException */ public Map getBookieInfo() throws BKException, InterruptedException { return bookieInfoReader.getBookieInfo(); } /** * Creates a new ledger asynchronously. To create a ledger, we need to specify * the ensemble size, the quorum size, the digest type, a password, a callback * implementation, and an optional control object. The ensemble size is how * many bookies the entries should be striped among and the quorum size is the * degree of replication of each entry. The digest type is either a MAC or a * CRC. Note that the CRC option is not able to protect a client against a * bookie that replaces an entry. The password is used not only to * authenticate access to a ledger, but also to verify entries in ledgers. * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to. each of these bookies * must acknowledge the entry before the call is completed. * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx) { asyncCreateLedger(ensSize, writeQuorumSize, writeQuorumSize, digestType, passwd, cb, ctx, Collections.emptyMap()); } /** * Creates a new ledger asynchronously. Ledgers created with this call have * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiate(); } finally { closeLock.readLock().unlock(); } } /** * Creates a new ledger. Default of 3 servers, and quorum of 2 servers. * * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(DigestType digestType, byte passwd[]) throws BKException, InterruptedException { return createLedger(3, 2, digestType, passwd); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param qSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int qSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, qSize, qSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of asyncCreateLedger * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateCallback result = new SyncCreateCallback(future); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} * which can accept entryId. Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } } /** * Synchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdvWithLedgerId * @param ledgerId * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(final long ledgerId, int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ledgerId, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } else if (ledgerId != lh.getId()) { LOG.error("Unexpected condition : Expected ledgerId: {} but got: {}", ledgerId, lh.getId()); throw BKException.create(BKException.Code.UnexpectedConditionException); } LOG.info("Ensemble: {} for ledger: {}", lh.getLedgerMetadata().getEnsembleAt(0L), lh.getId()); return lh; } /** * Asynchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of asyncCreateLedger * * @param ledgerId * ledger Id to use for the newly created ledger * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final long ledgerId, final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(ledgerId); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading. * * Opening a ledger with this method invokes fencing and recovery on the ledger * if the ledger has not been closed. Fencing will block all other clients from * writing to the ledger. Recovery will make sure that the ledger is closed * before reading from it. * * Recovery also makes sure that any entries which reached one bookie, but not a * quorum, will be replicated to a quorum of bookies. This occurs in cases were * the writer of a ledger crashes after sending a write request to one bookie but * before being able to send it to the rest of the bookies in the quorum. * * If the ledger is already closed, neither fencing nor recovery will be applied. * * @see LedgerHandle#asyncClose * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedger(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading, but it does not try to * recover the ledger if it is not yet closed. The application needs to use * it carefully, since the writer might have crashed and ledger will remain * unsealed forever if there is no external mechanism to detect the failure * of the writer and the ledger is not open in a safe manner, invoking the * recovery procedure. * * Opening a ledger without recovery does not fence the ledger. As such, other * clients can continue to write to the ledger. * * This method returns a read only ledger handle. It will not be possible * to add entries to the ledger. Any attempt to add entries will throw an * exception. * * Reads from the returned ledger will be able to read entries up until * the lastConfirmedEntry at the point in time at which the ledger was opened. * If an attempt is made to read beyond the ledger handle's LAC, an attempt is made * to get the latest LAC from bookies or metadata, and if the entry_id of the read request * is less than or equal to the new LAC, read will be allowed to proceed. * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedgerNoRecovery(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiateWithoutRecovery(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous open ledger call. * * @see #asyncOpenLedger * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedger(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedger(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Synchronous, unsafe open ledger call. * * @see #asyncOpenLedgerNoRecovery * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedgerNoRecovery(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedgerNoRecovery(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Deletes a ledger asynchronously. * * @param lId * ledger Id * @param cb * deleteCallback implementation * @param ctx * optional control object */ public void asyncDeleteLedger(final long lId, final DeleteCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.deleteComplete(BKException.Code.ClientClosedException, ctx); return; } new LedgerDeleteOp(BookKeeper.this, clientStats, lId, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous call to delete a ledger. Parameters match those of * {@link #asyncDeleteLedger(long, AsyncCallback.DeleteCallback, Object)} * * @param lId * ledgerId * @throws InterruptedException * @throws BKException */ public void deleteLedger(long lId) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); // Call asynchronous version asyncDeleteLedger(lId, result, null); SyncCallbackUtils.waitForResult(future); } /** * Check asynchronously whether the ledger with identifier lId * has been closed. * * @param lId ledger identifier * @param cb callback method */ public void asyncIsClosed(long lId, final IsClosedCallback cb, final Object ctx){ ledgerManager.readLedgerMetadata(lId).whenComplete((metadata, exception) -> { if (exception == null) { cb.isClosedComplete(BKException.Code.OK, metadata.getValue().isClosed(), ctx); } else { cb.isClosedComplete(BKException.getExceptionCode(exception), false, ctx); } }); } /** * Check whether the ledger with identifier lId * has been closed. * * @param lId * @return boolean true if ledger has been closed * @throws BKException */ public boolean isClosed(long lId) throws BKException, InterruptedException { final class Result { int rc; boolean isClosed; final CountDownLatch notifier = new CountDownLatch(1); } final Result result = new Result(); final IsClosedCallback cb = new IsClosedCallback(){ @Override public void isClosedComplete(int rc, boolean isClosed, Object ctx){ result.isClosed = isClosed; result.rc = rc; result.notifier.countDown(); } }; /* * Call asynchronous version of isClosed */ asyncIsClosed(lId, cb, null); /* * Wait for callback */ result.notifier.await(); if (result.rc != BKException.Code.OK) { throw BKException.create(result.rc); } return result.isClosed; } /** * Shuts down client. * */ @Override public void close() throws BKException, InterruptedException { closeLock.writeLock().lock(); try { if (closed) { return; } closed = true; } finally { closeLock.writeLock().unlock(); } // Close bookie client so all pending bookie requests would be failed // which will reject any incoming bookie requests. bookieClient.close(); try { // Close ledger manage so all pending metadata requests would be failed // which will reject any incoming metadata requests. ledgerManager.close(); ledgerIdGenerator.close(); } catch (IOException ie) { LOG.error("Failed to close ledger manager : ", ie); } // Close the scheduler scheduler.shutdown(); if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The scheduler did not shutdown cleanly"); } mainWorkerPool.shutdown(); if (!mainWorkerPool.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The mainWorkerPool did not shutdown cleanly"); } if (this.bookieInfoScheduler != null) { this.bookieInfoScheduler.shutdown(); if (!bookieInfoScheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The bookieInfoScheduler did not shutdown cleanly"); } } if (ownTimer) { requestTimer.stop(); } if (ownEventLoopGroup) { eventLoopGroup.shutdownGracefully(); } this.metadataDriver.close(); } @Override public CreateBuilder newCreateLedgerOp() { return new LedgerCreateOp.CreateBuilderImpl(this); } @Override public OpenBuilder newOpenLedgerOp() { return new LedgerOpenOp.OpenBuilderImpl(this); } @Override public DeleteBuilder newDeleteLedgerOp() { return new LedgerDeleteOp.DeleteBuilderImpl(this); } private final ClientContext clientCtx = new ClientContext() { @Override public ClientInternalConf getConf() { return internalConf; } @Override public LedgerManager getLedgerManager() { return BookKeeper.this.getLedgerManager(); } @Override public BookieWatcher getBookieWatcher() { return BookKeeper.this.getBookieWatcher(); } @Override public EnsemblePlacementPolicy getPlacementPolicy() { return BookKeeper.this.getPlacementPolicy(); } @Override public BookieClient getBookieClient() { return BookKeeper.this.getBookieClient(); } @Override public OrderedExecutor getMainWorkerPool() { return BookKeeper.this.getMainWorkerPool(); } @Override public OrderedScheduler getScheduler() { return BookKeeper.this.getScheduler(); } @Override public BookKeeperClientStats getClientStats() { return clientStats; } @Override public boolean isClientClosed() { return BookKeeper.this.isClosed(); } @Override public ByteBufAllocator getByteBufAllocator() { return allocator; } }; ClientContext getClientCtx() { return clientCtx; } } |
data class | 1. Long method | f | f | f | 1, ., , L, o, n, g, , m, e, t, h, o, d | data class | 0 | 2394 | https://github.com/apache/bookkeeper/blob/f26a4cae0e9205ad391c6d4d79f2937871864c28/bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookKeeper.java/#L103-L1511 | 2 | 221 | 2394 |
| 221 | { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BookKeeper implements org.apache.bookkeeper.client.api.BookKeeper { private static final Logger LOG = LoggerFactory.getLogger(BookKeeper.class); final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; // The stats logger for this client. private final StatsLogger statsLogger; private final BookKeeperClientStats clientStats; // whether the event loop group is one we created, or is owned by whoever // instantiated us boolean ownEventLoopGroup = false; final BookieClient bookieClient; final BookieWatcherImpl bookieWatcher; final OrderedExecutor mainWorkerPool; final OrderedScheduler scheduler; final HashedWheelTimer requestTimer; final boolean ownTimer; final FeatureProvider featureProvider; final ScheduledExecutorService bookieInfoScheduler; final MetadataClientDriver metadataDriver; // Ledger manager responsible for how to store ledger meta data final LedgerManagerFactory ledgerManagerFactory; final LedgerManager ledgerManager; final LedgerIdGenerator ledgerIdGenerator; // Ensemble Placement Policy final EnsemblePlacementPolicy placementPolicy; BookieInfoReader bookieInfoReader; final ClientConfiguration conf; final ClientInternalConf internalConf; // Close State boolean closed = false; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); /** * BookKeeper Client Builder to build client instances. * * @see BookKeeperBuilder */ public static class Builder { final ClientConfiguration conf; ZooKeeper zk = null; EventLoopGroup eventLoopGroup = null; ByteBufAllocator allocator = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; DNSToSwitchMapping dnsResolver = null; HashedWheelTimer requestTimer = null; FeatureProvider featureProvider = null; Builder(ClientConfiguration conf) { this.conf = conf; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #eventLoopGroup(EventLoopGroup)} * @see #eventLoopGroup(EventLoopGroup) */ @Deprecated public Builder setEventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #zk(ZooKeeper)} * @see #zk(ZooKeeper) */ @Deprecated public Builder setZookeeper(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @deprecated since 4.5, use {@link #statsLogger(StatsLogger)} * @see #statsLogger(StatsLogger) */ @Deprecated public Builder setStatsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @since 4.5 */ public Builder eventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ByteBufAllocator}. * * @param allocator an external {@link ByteBufAllocator} to use by the bookkeeper client. * @return client builder. * @since 4.9 */ public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @since 4.5 */ @Deprecated public Builder zk(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @since 4.5 */ public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client to use the provided dns resolver {@link DNSToSwitchMapping}. * * @param dnsResolver dns resolver for placement policy to use for resolving network locations. * @return client builder * @since 4.5 */ public Builder dnsResolver(DNSToSwitchMapping dnsResolver) { this.dnsResolver = dnsResolver; return this; } /** * Configure the bookkeeper client to use a provided {@link HashedWheelTimer}. * * @param requestTimer request timer for client to manage timer related tasks. * @return client builder * @since 4.5 */ public Builder requestTimer(HashedWheelTimer requestTimer) { this.requestTimer = requestTimer; return this; } /** * Feature Provider. * * @param featureProvider * @return */ public Builder featureProvider(FeatureProvider featureProvider) { this.featureProvider = featureProvider; return this; } public BookKeeper build() throws IOException, InterruptedException, BKException { checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, allocator, statsLogger, dnsResolver, requestTimer, featureProvider); } } public static Builder forConfig(final ClientConfiguration conf) { return new Builder(conf); } /** * Create a bookkeeper client. A zookeeper client and a client event loop group * will be instantiated as part of this constructor. * * @param servers * A list of one of more servers on which zookeeper is running. The * client assumes that the running bookies have been registered with * zookeeper under the path * {@link AbstractConfiguration#getZkAvailableBookiesPath()} * @throws IOException * @throws InterruptedException */ public BookKeeper(String servers) throws IOException, InterruptedException, BKException { this(new ClientConfiguration().setMetadataServiceUri("zk+null://" + servers + "/ledgers")); } /** * Create a bookkeeper client using a configuration object. * A zookeeper client and a client event loop group will be * instantiated as part of this constructor. * * @param conf * Client Configuration object * @throws IOException * @throws InterruptedException */ public BookKeeper(final ClientConfiguration conf) throws IOException, InterruptedException, BKException { this(conf, null, null, null, NullStatsLogger.INSTANCE, null, null, null); } private static ZooKeeper validateZooKeeper(ZooKeeper zk) throws NullPointerException, IOException { checkNotNull(zk, "No zookeeper instance provided"); if (!zk.getState().isConnected()) { LOG.error("Unconnected zookeeper handle passed to bookkeeper"); throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); } return zk; } private static EventLoopGroup validateEventLoopGroup(EventLoopGroup eventLoopGroup) throws NullPointerException { checkNotNull(eventLoopGroup, "No Event Loop Group provided"); return eventLoopGroup; } /** * Create a bookkeeper client but use the passed in zookeeper client instead * of instantiating one. * * @param conf * Client Configuration object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered * @throws IOException * @throws InterruptedException */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), null, null, NullStatsLogger.INSTANCE, null, null, null); } /** * Create a bookkeeper client but use the passed in zookeeper client and * client event loop group instead of instantiating those. * * @param conf * Client Configuration Object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered. The ZooKeeper client must be connected * before it is passed to BookKeeper. Otherwise a KeeperException is thrown. * @param eventLoopGroup * An event loop group that will be used to create connections to the bookies * @throws IOException * @throws InterruptedException * @throws BKException in the event of a bookkeeper connection error */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk, EventLoopGroup eventLoopGroup) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), validateEventLoopGroup(eventLoopGroup), null, NullStatsLogger.INSTANCE, null, null, null); } /** * Constructor for use with the builder. Other constructors also use it. */ @SuppressWarnings("deprecation") @VisibleForTesting BookKeeper(ClientConfiguration conf, ZooKeeper zkc, EventLoopGroup eventLoopGroup, ByteBufAllocator byteBufAllocator, StatsLogger rootStatsLogger, DNSToSwitchMapping dnsResolver, HashedWheelTimer requestTimer, FeatureProvider featureProvider) throws IOException, InterruptedException, BKException { this.conf = conf; // initialize feature provider if (null == featureProvider) { this.featureProvider = SettableFeatureProvider.DISABLE_ALL; } else { this.featureProvider = featureProvider; } this.internalConf = ClientInternalConf.fromConfigAndFeatureProvider(conf, this.featureProvider); // initialize resources this.scheduler = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("BookKeeperClientScheduler").build(); this.mainWorkerPool = OrderedExecutor.newBuilder() .name("BookKeeperClientWorker") .numThreads(conf.getNumWorkerThreads()) .statsLogger(rootStatsLogger) .traceTaskExecution(conf.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(conf.getPreserveMdcForTaskExecution()) .traceTaskWarnTimeMicroSec(conf.getTaskExecutionWarnTimeMicros()) .enableBusyWait(conf.isBusyWaitEnabled()) .build(); // initialize stats logger this.statsLogger = rootStatsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE); this.clientStats = BookKeeperClientStats.newInstance(this.statsLogger); // initialize metadata driver try { String metadataServiceUriStr = conf.getMetadataServiceUri(); if (null != metadataServiceUriStr) { this.metadataDriver = MetadataDrivers.getClientDriver(URI.create(metadataServiceUriStr)); } else { checkNotNull(zkc, "No external zookeeper provided when no metadata service uri is found"); this.metadataDriver = MetadataDrivers.getClientDriver("zk"); } this.metadataDriver.initialize( conf, scheduler, rootStatsLogger, java.util.Optional.ofNullable(zkc)); } catch (ConfigurationException ce) { LOG.error("Failed to initialize metadata client driver using invalid metadata service uri", ce); throw new IOException("Failed to initialize metadata client driver", ce); } catch (MetadataException me) { LOG.error("Encountered metadata exceptions on initializing metadata client driver", me); throw new IOException("Failed to initialize metadata client driver", me); } // initialize event loop group if (null == eventLoopGroup) { this.eventLoopGroup = EventLoopUtil.getClientEventLoopGroup(conf, new DefaultThreadFactory("bookkeeper-io")); this.ownEventLoopGroup = true; } else { this.eventLoopGroup = eventLoopGroup; this.ownEventLoopGroup = false; } if (byteBufAllocator != null) { this.allocator = byteBufAllocator; } else { this.allocator = ByteBufAllocatorBuilder.create() .poolingPolicy(conf.getAllocatorPoolingPolicy()) .poolingConcurrency(conf.getAllocatorPoolingConcurrency()) .outOfMemoryPolicy(conf.getAllocatorOutOfMemoryPolicy()) .leakDetectionPolicy(conf.getAllocatorLeakDetectionPolicy()) .build(); } // initialize bookie client this.bookieClient = new BookieClientImpl(conf, this.eventLoopGroup, this.allocator, this.mainWorkerPool, scheduler, rootStatsLogger); if (null == requestTimer) { this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieClientTimer-%d").build(), conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS, conf.getTimeoutTimerNumTicks()); this.ownTimer = true; } else { this.requestTimer = requestTimer; this.ownTimer = false; } // initialize the ensemble placement this.placementPolicy = initializeEnsemblePlacementPolicy(conf, dnsResolver, this.requestTimer, this.featureProvider, this.statsLogger); this.bookieWatcher = new BookieWatcherImpl( conf, this.placementPolicy, metadataDriver.getRegistrationClient(), this.statsLogger.scope(WATCHER_SCOPE)); if (conf.getDiskWeightBasedPlacementEnabled()) { LOG.info("Weighted ledger placement enabled"); ThreadFactoryBuilder tFBuilder = new ThreadFactoryBuilder() .setNameFormat("BKClientMetaDataPollScheduler-%d"); this.bookieInfoScheduler = Executors.newSingleThreadScheduledExecutor(tFBuilder.build()); this.bookieInfoReader = new BookieInfoReader(this, conf, this.bookieInfoScheduler); this.bookieWatcher.initialBlockingBookieRead(); this.bookieInfoReader.start(); } else { LOG.info("Weighted ledger placement is not enabled"); this.bookieInfoScheduler = null; this.bookieInfoReader = new BookieInfoReader(this, conf, null); this.bookieWatcher.initialBlockingBookieRead(); } // initialize ledger manager try { this.ledgerManagerFactory = this.metadataDriver.getLedgerManagerFactory(); } catch (MetadataException e) { throw new IOException("Failed to initialize ledger manager factory", e); } this.ledgerManager = new CleanupLedgerManager(ledgerManagerFactory.newLedgerManager()); this.ledgerIdGenerator = ledgerManagerFactory.newLedgerIdGenerator(); scheduleBookieHealthCheckIfEnabled(conf); } /** * Allow to extend BookKeeper for mocking in unit tests. */ @VisibleForTesting BookKeeper() { conf = new ClientConfiguration(); internalConf = ClientInternalConf.fromConfig(conf); statsLogger = NullStatsLogger.INSTANCE; clientStats = BookKeeperClientStats.newInstance(statsLogger); scheduler = null; requestTimer = null; metadataDriver = null; placementPolicy = null; ownTimer = false; mainWorkerPool = null; ledgerManagerFactory = null; ledgerManager = null; ledgerIdGenerator = null; featureProvider = null; eventLoopGroup = null; bookieWatcher = null; bookieInfoScheduler = null; bookieClient = null; allocator = UnpooledByteBufAllocator.DEFAULT; } private EnsemblePlacementPolicy initializeEnsemblePlacementPolicy(ClientConfiguration conf, DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, FeatureProvider featureProvider, StatsLogger statsLogger) throws IOException { try { Class policyCls = conf.getEnsemblePlacementPolicy(); return ReflectionUtils.newInstance(policyCls).initialize(conf, java.util.Optional.ofNullable(dnsResolver), timer, featureProvider, statsLogger); } catch (ConfigurationException e) { throw new IOException("Failed to initialize ensemble placement policy : ", e); } } int getReturnRc(int rc) { return getReturnRc(bookieClient, rc); } static int getReturnRc(BookieClient bookieClient, int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (bookieClient.isClosed()) { return BKException.Code.ClientClosedException; } else { return rc; } } } void scheduleBookieHealthCheckIfEnabled(ClientConfiguration conf) { if (conf.isBookieHealthCheckEnabled()) { scheduler.scheduleAtFixedRate(new SafeRunnable() { @Override public void safeRun() { checkForFaultyBookies(); } }, conf.getBookieHealthCheckIntervalSeconds(), conf.getBookieHealthCheckIntervalSeconds(), TimeUnit.SECONDS); } } void checkForFaultyBookies() { List faultyBookies = bookieClient.getFaultyBookies(); for (BookieSocketAddress faultyBookie : faultyBookies) { bookieWatcher.quarantineBookie(faultyBookie); } } /** * Returns ref to speculative read counter, needed in PendingReadOp. */ @VisibleForTesting public LedgerManager getLedgerManager() { return ledgerManager; } @VisibleForTesting LedgerManager getUnderlyingLedgerManager() { return ((CleanupLedgerManager) ledgerManager).getUnderlying(); } @VisibleForTesting LedgerIdGenerator getLedgerIdGenerator() { return ledgerIdGenerator; } @VisibleForTesting ReentrantReadWriteLock getCloseLock() { return closeLock; } @VisibleForTesting boolean isClosed() { return closed; } @VisibleForTesting BookieWatcher getBookieWatcher() { return bookieWatcher; } public OrderedExecutor getMainWorkerPool() { return mainWorkerPool; } @VisibleForTesting OrderedScheduler getScheduler() { return scheduler; } @VisibleForTesting EnsemblePlacementPolicy getPlacementPolicy() { return placementPolicy; } @VisibleForTesting public MetadataClientDriver getMetadataClientDriver() { return metadataDriver; } /** * There are 3 digest types that can be used for verification. The CRC32 is * cheap to compute but does not protect against byzantine bookies (i.e., a * bookie might report fake bytes and a matching CRC32). The MAC code is more * expensive to compute, but is protected by a password, i.e., a bookie can't * report fake bytes with a mathching MAC unless it knows the password. * The CRC32C, which use SSE processor instruction, has better performance than CRC32. * Legacy DigestType for backward compatibility. If we want to add new DigestType, * we should add it in here, client.api.DigestType and DigestType in DataFormats.proto. * If the digest type is set/passed in as DUMMY, a dummy digest is added/checked. * This DUMMY digest is mostly for test purposes or in situations/use-cases * where digest is considered a overhead. */ public enum DigestType { MAC, CRC32, CRC32C, DUMMY; public static DigestType fromApiDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { switch (digestType) { case MAC: return DigestType.MAC; case CRC32: return DigestType.CRC32; case CRC32C: return DigestType.CRC32C; case DUMMY: return DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public static DataFormats.LedgerMetadataFormat.DigestType toProtoDigestType(DigestType digestType) { switch (digestType) { case MAC: return DataFormats.LedgerMetadataFormat.DigestType.HMAC; case CRC32: return DataFormats.LedgerMetadataFormat.DigestType.CRC32; case CRC32C: return DataFormats.LedgerMetadataFormat.DigestType.CRC32C; case DUMMY: return DataFormats.LedgerMetadataFormat.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public org.apache.bookkeeper.client.api.DigestType toApiDigestType() { switch (this) { case MAC: return org.apache.bookkeeper.client.api.DigestType.MAC; case CRC32: return org.apache.bookkeeper.client.api.DigestType.CRC32; case CRC32C: return org.apache.bookkeeper.client.api.DigestType.CRC32C; case DUMMY: return org.apache.bookkeeper.client.api.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + this); } } } ZooKeeper getZkHandle() { return ((ZKMetadataClientDriver) metadataDriver).getZk(); } protected ClientConfiguration getConf() { return conf; } StatsLogger getStatsLogger() { return statsLogger; } /** * Get the BookieClient, currently used for doing bookie recovery. * * @return BookieClient for the BookKeeper instance. */ BookieClient getBookieClient() { return bookieClient; } /** * Retrieves BookieInfo from all the bookies in the cluster. It sends requests * to all the bookies in parallel and returns the info from the bookies that responded. * If there was an error in reading from any bookie, nothing will be returned for * that bookie in the map. * @return map * A map of bookieSocketAddress to its BookiInfo * @throws BKException * @throws InterruptedException */ public Map getBookieInfo() throws BKException, InterruptedException { return bookieInfoReader.getBookieInfo(); } /** * Creates a new ledger asynchronously. To create a ledger, we need to specify * the ensemble size, the quorum size, the digest type, a password, a callback * implementation, and an optional control object. The ensemble size is how * many bookies the entries should be striped among and the quorum size is the * degree of replication of each entry. The digest type is either a MAC or a * CRC. Note that the CRC option is not able to protect a client against a * bookie that replaces an entry. The password is used not only to * authenticate access to a ledger, but also to verify entries in ledgers. * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to. each of these bookies * must acknowledge the entry before the call is completed. * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx) { asyncCreateLedger(ensSize, writeQuorumSize, writeQuorumSize, digestType, passwd, cb, ctx, Collections.emptyMap()); } /** * Creates a new ledger asynchronously. Ledgers created with this call have * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiate(); } finally { closeLock.readLock().unlock(); } } /** * Creates a new ledger. Default of 3 servers, and quorum of 2 servers. * * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(DigestType digestType, byte passwd[]) throws BKException, InterruptedException { return createLedger(3, 2, digestType, passwd); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param qSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int qSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, qSize, qSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of asyncCreateLedger * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateCallback result = new SyncCreateCallback(future); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} * which can accept entryId. Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } } /** * Synchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdvWithLedgerId * @param ledgerId * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(final long ledgerId, int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ledgerId, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } else if (ledgerId != lh.getId()) { LOG.error("Unexpected condition : Expected ledgerId: {} but got: {}", ledgerId, lh.getId()); throw BKException.create(BKException.Code.UnexpectedConditionException); } LOG.info("Ensemble: {} for ledger: {}", lh.getLedgerMetadata().getEnsembleAt(0L), lh.getId()); return lh; } /** * Asynchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of asyncCreateLedger * * @param ledgerId * ledger Id to use for the newly created ledger * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final long ledgerId, final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(ledgerId); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading. * * Opening a ledger with this method invokes fencing and recovery on the ledger * if the ledger has not been closed. Fencing will block all other clients from * writing to the ledger. Recovery will make sure that the ledger is closed * before reading from it. * * Recovery also makes sure that any entries which reached one bookie, but not a * quorum, will be replicated to a quorum of bookies. This occurs in cases were * the writer of a ledger crashes after sending a write request to one bookie but * before being able to send it to the rest of the bookies in the quorum. * * If the ledger is already closed, neither fencing nor recovery will be applied. * * @see LedgerHandle#asyncClose * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedger(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading, but it does not try to * recover the ledger if it is not yet closed. The application needs to use * it carefully, since the writer might have crashed and ledger will remain * unsealed forever if there is no external mechanism to detect the failure * of the writer and the ledger is not open in a safe manner, invoking the * recovery procedure. * * Opening a ledger without recovery does not fence the ledger. As such, other * clients can continue to write to the ledger. * * This method returns a read only ledger handle. It will not be possible * to add entries to the ledger. Any attempt to add entries will throw an * exception. * * Reads from the returned ledger will be able to read entries up until * the lastConfirmedEntry at the point in time at which the ledger was opened. * If an attempt is made to read beyond the ledger handle's LAC, an attempt is made * to get the latest LAC from bookies or metadata, and if the entry_id of the read request * is less than or equal to the new LAC, read will be allowed to proceed. * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedgerNoRecovery(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiateWithoutRecovery(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous open ledger call. * * @see #asyncOpenLedger * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedger(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedger(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Synchronous, unsafe open ledger call. * * @see #asyncOpenLedgerNoRecovery * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedgerNoRecovery(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedgerNoRecovery(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Deletes a ledger asynchronously. * * @param lId * ledger Id * @param cb * deleteCallback implementation * @param ctx * optional control object */ public void asyncDeleteLedger(final long lId, final DeleteCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.deleteComplete(BKException.Code.ClientClosedException, ctx); return; } new LedgerDeleteOp(BookKeeper.this, clientStats, lId, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous call to delete a ledger. Parameters match those of * {@link #asyncDeleteLedger(long, AsyncCallback.DeleteCallback, Object)} * * @param lId * ledgerId * @throws InterruptedException * @throws BKException */ public void deleteLedger(long lId) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); // Call asynchronous version asyncDeleteLedger(lId, result, null); SyncCallbackUtils.waitForResult(future); } /** * Check asynchronously whether the ledger with identifier lId * has been closed. * * @param lId ledger identifier * @param cb callback method */ public void asyncIsClosed(long lId, final IsClosedCallback cb, final Object ctx){ ledgerManager.readLedgerMetadata(lId).whenComplete((metadata, exception) -> { if (exception == null) { cb.isClosedComplete(BKException.Code.OK, metadata.getValue().isClosed(), ctx); } else { cb.isClosedComplete(BKException.getExceptionCode(exception), false, ctx); } }); } /** * Check whether the ledger with identifier lId * has been closed. * * @param lId * @return boolean true if ledger has been closed * @throws BKException */ public boolean isClosed(long lId) throws BKException, InterruptedException { final class Result { int rc; boolean isClosed; final CountDownLatch notifier = new CountDownLatch(1); } final Result result = new Result(); final IsClosedCallback cb = new IsClosedCallback(){ @Override public void isClosedComplete(int rc, boolean isClosed, Object ctx){ result.isClosed = isClosed; result.rc = rc; result.notifier.countDown(); } }; /* * Call asynchronous version of isClosed */ asyncIsClosed(lId, cb, null); /* * Wait for callback */ result.notifier.await(); if (result.rc != BKException.Code.OK) { throw BKException.create(result.rc); } return result.isClosed; } /** * Shuts down client. * */ @Override public void close() throws BKException, InterruptedException { closeLock.writeLock().lock(); try { if (closed) { return; } closed = true; } finally { closeLock.writeLock().unlock(); } // Close bookie client so all pending bookie requests would be failed // which will reject any incoming bookie requests. bookieClient.close(); try { // Close ledger manage so all pending metadata requests would be failed // which will reject any incoming metadata requests. ledgerManager.close(); ledgerIdGenerator.close(); } catch (IOException ie) { LOG.error("Failed to close ledger manager : ", ie); } // Close the scheduler scheduler.shutdown(); if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The scheduler did not shutdown cleanly"); } mainWorkerPool.shutdown(); if (!mainWorkerPool.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The mainWorkerPool did not shutdown cleanly"); } if (this.bookieInfoScheduler != null) { this.bookieInfoScheduler.shutdown(); if (!bookieInfoScheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The bookieInfoScheduler did not shutdown cleanly"); } } if (ownTimer) { requestTimer.stop(); } if (ownEventLoopGroup) { eventLoopGroup.shutdownGracefully(); } this.metadataDriver.close(); } @Override public CreateBuilder newCreateLedgerOp() { return new LedgerCreateOp.CreateBuilderImpl(this); } @Override public OpenBuilder newOpenLedgerOp() { return new LedgerOpenOp.OpenBuilderImpl(this); } @Override public DeleteBuilder newDeleteLedgerOp() { return new LedgerDeleteOp.DeleteBuilderImpl(this); } private final ClientContext clientCtx = new ClientContext() { @Override public ClientInternalConf getConf() { return internalConf; } @Override public LedgerManager getLedgerManager() { return BookKeeper.this.getLedgerManager(); } @Override public BookieWatcher getBookieWatcher() { return BookKeeper.this.getBookieWatcher(); } @Override public EnsemblePlacementPolicy getPlacementPolicy() { return BookKeeper.this.getPlacementPolicy(); } @Override public BookieClient getBookieClient() { return BookKeeper.this.getBookieClient(); } @Override public OrderedExecutor getMainWorkerPool() { return BookKeeper.this.getMainWorkerPool(); } @Override public OrderedScheduler getScheduler() { return BookKeeper.this.getScheduler(); } @Override public BookKeeperClientStats getClientStats() { return clientStats; } @Override public boolean isClientClosed() { return BookKeeper.this.isClosed(); } @Override public ByteBufAllocator getByteBufAllocator() { return allocator; } }; ClientContext getClientCtx() { return clientCtx; } } |
data class | true, "the bad smells are" | t | f | f | true, "the bad smells are" | data class | 0 | 2394 | https://github.com/apache/bookkeeper/blob/f26a4cae0e9205ad391c6d4d79f2937871864c28/bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookKeeper.java/#L103-L1511 | 1 | 221 | 2394 |
| 224 | { "message": "YES I found bad smells", "bad smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processSelectedKeys() { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); final SelectableChannel sc = key.channel(); // do not attempt to read/write until handle is set (e.g. after handshake is completed) if (key.isReadable() && key.attachment() != null) { read(key); } else if (key.isWritable() && key.attachment() != null) { write(key); } else if (key.isAcceptable()) { assert sc == serverSocketChannel; accept(); } else if (key.isConnectable()) { finishConnect(key); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2418 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/impl/IPCConnectionManager.java/#L213-L230 | 1 | 224 | 2418 | |
| 224 | { "response": "YES, I found bad smells", "the bad smells are": [ "1. Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processSelectedKeys() { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); final SelectableChannel sc = key.channel(); // do not attempt to read/write until handle is set (e.g. after handshake is completed) if (key.isReadable() && key.attachment() != null) { read(key); } else if (key.isWritable() && key.attachment() != null) { write(key); } else if (key.isAcceptable()) { assert sc == serverSocketChannel; accept(); } else if (key.isConnectable()) { finishConnect(key); } } } |
long method | 1. long method | t | t | t | 0 | 2418 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/impl/IPCConnectionManager.java/#L213-L230 | 2 | 224 | 2418 | ||
| 225 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TwitterPullRecordReader implements IRecordReader { private Query query; private Twitter twitter; private int requestInterval = 5; // seconds private QueryResult result; private int nextTweetIndex = 0; private long lastTweetIdReceived = 0; private CharArrayRecord record; private boolean stopped = false; public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new CharArrayRecord(); } @Override public void close() throws IOException { // do nothing } @Override public boolean hasNext() throws Exception { return !stopped; } @Override public IRawRecord next() throws IOException, InterruptedException { if (result == null || nextTweetIndex >= result.getTweets().size()) { Thread.sleep(1000 * requestInterval); query.setSinceId(lastTweetIdReceived); try { result = twitter.search(query); } catch (TwitterException e) { throw HyracksDataException.create(e); } nextTweetIndex = 0; } if (result != null && !result.getTweets().isEmpty()) { List tw = result.getTweets(); Status tweet = tw.get(nextTweetIndex++); if (lastTweetIdReceived < tweet.getId()) { lastTweetIdReceived = tweet.getId(); } String jsonTweet = TwitterObjectFactory.getRawJSON(tweet); // transform tweet obj to json record.set(jsonTweet); return record; } else { return null; } } @Override public boolean stop() { stopped = true; return true; } @Override public void setFeedLogManager(FeedLogManager feedLogManager) { // do nothing } @Override public void setController(AbstractFeedDataFlowController controller) { // do nothing } @Override public boolean handleException(Throwable th) { return false; } } |
data class | long method, data class | t | t | t | long method | 0 | 2434 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/twitter/TwitterPullRecordReader.java/#L38-L113 | 1 | 225 | 2434 | |
| 225 | {"response": "YES, I found bad smells", "bad smells are:": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TwitterPullRecordReader implements IRecordReader { private Query query; private Twitter twitter; private int requestInterval = 5; // seconds private QueryResult result; private int nextTweetIndex = 0; private long lastTweetIdReceived = 0; private CharArrayRecord record; private boolean stopped = false; public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new CharArrayRecord(); } @Override public void close() throws IOException { // do nothing } @Override public boolean hasNext() throws Exception { return !stopped; } @Override public IRawRecord next() throws IOException, InterruptedException { if (result == null || nextTweetIndex >= result.getTweets().size()) { Thread.sleep(1000 * requestInterval); query.setSinceId(lastTweetIdReceived); try { result = twitter.search(query); } catch (TwitterException e) { throw HyracksDataException.create(e); } nextTweetIndex = 0; } if (result != null && !result.getTweets().isEmpty()) { List tw = result.getTweets(); Status tweet = tw.get(nextTweetIndex++); if (lastTweetIdReceived < tweet.getId()) { lastTweetIdReceived = tweet.getId(); } String jsonTweet = TwitterObjectFactory.getRawJSON(tweet); // transform tweet obj to json record.set(jsonTweet); return record; } else { return null; } } @Override public boolean stop() { stopped = true; return true; } @Override public void setFeedLogManager(FeedLogManager feedLogManager) { // do nothing } @Override public void setController(AbstractFeedDataFlowController controller) { // do nothing } @Override public boolean handleException(Throwable th) { return false; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2434 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/twitter/TwitterPullRecordReader.java/#L38-L113 | 2 | 225 | 2434 |
| 227 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2450 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 2 | 227 | 2450 |
| 227 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | data class | t | t | t | 0 | 2450 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 1 | 227 | 2450 | ||
| 228 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | long method | t | t | f | long method | data class | 0 | 2451 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 1 | 228 | 2451 |
| 228 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2451 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 2 | 228 | 2451 |
| 229 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | data class, long method | t | t | t | long method | 0 | 2506 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 229 | 2506 | |
| 229 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2506 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 229 | 2506 |
| 230 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2513 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 230 | 2513 | |
| 230 | { "response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2513 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 230 | 2513 | |
| 232 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
long method | long method, data class | t | t | t | data class | 0 | 2538 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 1 | 232 | 2538 | |
| 232 | {"message": "YES, I found bad smells", "bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2538 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 2 | 232 | 2538 | |
| 238 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | 1. data class | t | t | t | 0 | 2613 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 238 | 2613 | ||
| 238 | {"response": "YES I found bad smells", "the bad smells are": [ "Long method", "Data class", "Data clumps" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | long method, data class, data clumps | t | t | t | long method, data clumps | 0 | 2613 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 238 | 2613 | |
| 240 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2628 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 2 | 240 | 2628 | |
| 240 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | long method | t | t | t | 0 | 2628 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 1 | 240 | 2628 | ||
| 241 | { "output": "YES I found bad smells", "the bad smells are": [ "Long method", "Duplicate code", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | long method, duplicate code, feature envy | t | t | f | long method, duplicate code, feature envy | data class | 0 | 2643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 241 | 2643 |
| 243 | {"message": "YES, I found bad smells", "bad_smells": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2648 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 2 | 243 | 2648 |
| 246 | { "message": "YES I found bad smells", "bad_smells_are": ["1. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | 1. data class | t | t | t | 0 | 2654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 1 | 246 | 2654 | ||
| 246 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 2 | 246 | 2654 |
| 249 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | data class | t | t | t | 0 | 2663 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 1 | 249 | 2663 | ||
| 249 | {"message": "YES I found bad smells, the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2663 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 2 | 249 | 2663 |
| 250 | {"message": "YES I found bad smells", "bad smells are": ["1.Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | 1.long method | t | t | f | 1.long method | data class | 0 | 2685 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 2 | 250 | 2685 |
| 250 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | long method, data class | t | t | t | long method | 0 | 2685 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 1 | 250 | 2685 | |
| 251 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public final class ShortSerializer extends TypeSerializerSingleton { private static final long serialVersionUID = 1L; /** Sharable instance of the ShortSerializer. */ public static final ShortSerializer INSTANCE = new ShortSerializer(); private static final Short ZERO = (short) 0; @Override public boolean isImmutableType() { return true; } @Override public Short createInstance() { return ZERO; } @Override public Short copy(Short from) { return from; } @Override public Short copy(Short from, Short reuse) { return from; } @Override public int getLength() { return 2; } @Override public void serialize(Short record, DataOutputView target) throws IOException { target.writeShort(record); } @Override public Short deserialize(DataInputView source) throws IOException { return source.readShort(); } @Override public Short deserialize(Short reuse, DataInputView source) throws IOException { return deserialize(source); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { target.writeShort(source.readShort()); } @Override public TypeSerializerSnapshot snapshotConfiguration() { return new ShortSerializerSnapshot(); } // ------------------------------------------------------------------------ /** * Serializer configuration snapshot for compatibility and format evolution. */ @SuppressWarnings("WeakerAccess") public static final class ShortSerializerSnapshot extends SimpleTypeSerializerSnapshot { public ShortSerializerSnapshot() { super(() -> INSTANCE); } } } |
data class | Not specified | f | f | f | false | 0 | 2690 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortSerializer.java/#L32-L104 | 2 | 251 | 2690 | |
| 251 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public final class ShortSerializer extends TypeSerializerSingleton { private static final long serialVersionUID = 1L; /** Sharable instance of the ShortSerializer. */ public static final ShortSerializer INSTANCE = new ShortSerializer(); private static final Short ZERO = (short) 0; @Override public boolean isImmutableType() { return true; } @Override public Short createInstance() { return ZERO; } @Override public Short copy(Short from) { return from; } @Override public Short copy(Short from, Short reuse) { return from; } @Override public int getLength() { return 2; } @Override public void serialize(Short record, DataOutputView target) throws IOException { target.writeShort(record); } @Override public Short deserialize(DataInputView source) throws IOException { return source.readShort(); } @Override public Short deserialize(Short reuse, DataInputView source) throws IOException { return deserialize(source); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { target.writeShort(source.readShort()); } @Override public TypeSerializerSnapshot snapshotConfiguration() { return new ShortSerializerSnapshot(); } // ------------------------------------------------------------------------ /** * Serializer configuration snapshot for compatibility and format evolution. */ @SuppressWarnings("WeakerAccess") public static final class ShortSerializerSnapshot extends SimpleTypeSerializerSnapshot { public ShortSerializerSnapshot() { super(() -> INSTANCE); } } } |
data class | long method, data class | t | t | t | long method | 0 | 2690 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortSerializer.java/#L32-L104 | 1 | 251 | 2690 | |
| 254 | { "message": "YES I found bad smells", "bad smells are": ["1.Long method"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | 1.long method | t | t | t | 0 | 2738 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 254 | 2738 | ||
| 254 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2738 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 254 | 2738 | |
| 256 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2765 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 2 | 256 | 2765 |
| 256 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | 1. data class | t | t | t | 0 | 2765 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 1 | 256 | 2765 | ||
| 257 | { "response": "YES, I found bad smells", "bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String command() { String flags; if (add) { flags = " +FLAGS "; } else if (subtract) { flags = " -FLAGS "; } else { flags = " FLAGS "; } if (silent) { flags = flags + ".SILENT"; } return "STORE " + msn + flags + this.flags + ")"; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2777 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mpt/core/src/main/java/org/apache/james/mpt/helper/ScriptBuilder.java/#L604-L617 | 2 | 257 | 2777 | |
| 257 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String command() { String flags; if (add) { flags = " +FLAGS "; } else if (subtract) { flags = " -FLAGS "; } else { flags = " FLAGS "; } if (silent) { flags = flags + ".SILENT"; } return "STORE " + msn + flags + this.flags + ")"; } |
long method | long method | t | t | t | 0 | 2777 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mpt/core/src/main/java/org/apache/james/mpt/helper/ScriptBuilder.java/#L604-L617 | 1 | 257 | 2777 | ||
| 258 | {"message": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int width = (int) Math.ceil(2 / sketch.getRelativeError()); int depth = (int) Math.ceil(-Math.log(1 - sketch.getConfidence()) / Math.log(2)); return new AutoValue_SketchFrequencies_Sketch<>(depth, width, sketch); } |
long method | long method | t | t | t | 0 | 2807 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sketching/src/main/java/org/apache/beam/sdk/extensions/sketching/SketchFrequencies.java/#L464-L468 | 1 | 258 | 2807 | ||
| 258 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int width = (int) Math.ceil(2 / sketch.getRelativeError()); int depth = (int) Math.ceil(-Math.log(1 - sketch.getConfidence()) / Math.log(2)); return new AutoValue_SketchFrequencies_Sketch<>(depth, width, sketch); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2807 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sketching/src/main/java/org/apache/beam/sdk/extensions/sketching/SketchFrequencies.java/#L464-L468 | 2 | 258 | 2807 | |
| 259 | {"output": "YES I found bad smells\nthe bad smells are: 1. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | 1. data class | t | t | t | 0 | 2812 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 1 | 259 | 2812 | ||
| 259 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | long method | t | t | f | long method | data class | 0 | 2812 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 2 | 259 | 2812 |
| 261 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2843 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 261 | 2843 | |
| 261 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | long method, data class | t | t | t | data class | 0 | 2843 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 261 | 2843 | |
| 262 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 2850 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 262 | 2850 |
| 262 | {"message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2850 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 262 | 2850 |
| 267 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } } |
data class | long method, data class | t | t | t | long method | 0 | 2884 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 | 1 | 267 | 2884 | |
| 267 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2884 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 | 2 | 267 | 2884 |
| 268 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | f | f | f | data class | 0 | 2887 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 268 | 2887 | |||
| 268 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | long method | t | t | f | long method | data class | 0 | 2887 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 1 | 268 | 2887 |
| 269 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | data class | t | t | t | 0 | 2890 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 1 | 269 | 2890 | ||
| 269 | {"response": "YES I found bad smells", "the bad smells are": [ "1. Long method" ]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2890 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 269 | 2890 |
| 270 | {"response": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T callWithTimeout(Callable callable, long timeoutDuration, TimeUnit timeoutUnit) throws ExecutionException { checkNotNull(callable); checkNotNull(timeoutUnit); try { return callable.call(); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } catch (Throwable e) { // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend // Exception, so we'll treat it like an Exception. throw new ExecutionException(e); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2901 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java/#L49-L67 | 2 | 270 | 2901 | |
| 270 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T callWithTimeout(Callable callable, long timeoutDuration, TimeUnit timeoutUnit) throws ExecutionException { checkNotNull(callable); checkNotNull(timeoutUnit); try { return callable.call(); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } catch (Throwable e) { // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend // Exception, so we'll treat it like an Exception. throw new ExecutionException(e); } } |
long method | 1. long method | t | t | t | 0 | 2901 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java/#L49-L67 | 1 | 270 | 2901 | ||
| 273 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2935 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 273 | 2935 |
| 273 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2935 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 273 | 2935 |
| 276 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | long method, data class | t | t | t | data class | 0 | 2964 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 276 | 2964 | |
| 276 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method 2Feature envy | t | f | t | 0 | 2964 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 276 | 2964 | ||
| 279 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Wrap extends DoFn> { @ProcessElement public void processElement(ProcessContext ctx) { ctx.output(KV.of(ctx.timestamp().getMillis(), ctx.element())); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2988 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/euphoria/src/main/java/org/apache/beam/sdk/extensions/euphoria/core/translate/TimestampExtractTransform.java/#L78-L84 | 1 | 279 | 2988 |
| 279 | YES I found bad smells the bad smells are: 1.Long method, 2.Inline code, 3.Poor naming convention | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Wrap extends DoFn> { @ProcessElement public void processElement(ProcessContext ctx) { ctx.output(KV.of(ctx.timestamp().getMillis(), ctx.element())); } } |
data class | Long method, 2Inline code, 3Poor naming convention | t | f | f | .Long method, 2.Inline code, 3.Poor naming convention | data class | 0 | 2988 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/euphoria/src/main/java/org/apache/beam/sdk/extensions/euphoria/core/translate/TimestampExtractTransform.java/#L78-L84 | 2 | 279 | 2988 |
| 280 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | data class | t | t | t | 0 | 3003 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 1 | 280 | 3003 | ||
| 280 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3003 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 2 | 280 | 3003 |
| 281 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
long method | long method | t | t | t | 0 | 3011 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 1 | 281 | 3011 | ||
| 281 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Use of magic numbers 5. Inconsistent formatting 6. Mixing of business logic and presentation (the use of LOGGER to output an error message) 7. Potential null pointer exception (if maxFiles is null) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
long method | Long method2 Feature envy3 Primitive obsession4 Use of magic numbers5 Inconsistent formatting 6 Mixing of business logic and presentation (the use of LOGGER to output an error message) 7 Potential null pointer exception (if maxFiles is null) | t | f | t | 0 | 3011 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 2 | 281 | 3011 | ||
| 284 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ManagedAttributeValueType public interface AclRule extends ManagedAttributeValue { String getIdentity(); ObjectType getObjectType(); LegacyOperation getOperation(); Map getAttributes(); RuleOutcome getOutcome(); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 3039 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AclRule.java/#L31-L39 | 2 | 284 | 3039 |
| 285 | { "response": "YES I found bad smells", "detected_bad_smells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void securityConfEdited() { // Need to call explicitly since we will not get notified of changes to local security.json cores.securityNodeChanged(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3055 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/admin/SecurityConfHandlerLocal.java/#L99-L103 | 1 | 285 | 3055 |
| 285 | YES, I found bad smells the bad smells are: 1. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void securityConfEdited() { // Need to call explicitly since we will not get notified of changes to local security.json cores.securityNodeChanged(); } |
feature envy | Magic numbers | t | f | f | . Magic numbers | feature envy | 0 | 3055 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/admin/SecurityConfHandlerLocal.java/#L99-L103 | 2 | 285 | 3055 |
| 287 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
long method | 1. long method | t | t | t | 0 | 3060 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 287 | 3060 | ||
| 287 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
long method | Long method | t | f | t | 0 | 3060 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 287 | 3060 | ||
| 288 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3061 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 288 | 3061 |
| 288 | YES I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 3061 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 288 | 3061 | |
| 289 | { "message": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | 1. data class | t | t | t | 0 | 3068 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 1 | 289 | 3068 | ||
| 289 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 3068 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 2 | 289 | 3068 |
| 292 | YES I found bad smells The bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Null checks/Exception handling inside a method 5. Magic numbers 6. Multiple assertions in one test method 7. Testing implementation details instead of behavior 8. Lack of descriptive method and variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
data class | Duplicated code2 Long method3 Feature envy4 Null checks/Exception handling inside a method5 Magic numbers6 Multiple assertions in one test method7 Testing implementation details instead of behavior8 Lack of descriptive method and variable names | t | f | f | . Duplicated code2. Long method3. Feature envy4. Null checks/Exception handling inside a method5. Magic numbers6. Multiple assertions in one test method7. Testing implementation details instead of behavior8. Lack of descriptive method and variable names | data class | 0 | 3077 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 2 | 292 | 3077 |
| 292 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
data class | long method | t | t | f | long method | data class | 0 | 3077 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 1 | 292 | 3077 |
| 295 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | 1. long method | t | t | t | 0 | 3109 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 1 | 295 | 3109 | ||
| 295 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3109 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 2 | 295 | 3109 | ||
| 296 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | data class, long method | t | t | t | long method | 0 | 3115 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 1 | 296 | 3115 | |
| 296 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 3115 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 2 | 296 | 3115 |
| 298 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | data class | t | t | t | 0 | 3132 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 1 | 298 | 3132 | ||
| 298 | YES I found bad smells the bad smells are: 1.Dead code, 2.The class is annotated as deprecated but it does not have any Deprecated annotation or comment. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Dead code, 2The class is annotated as deprecated but it does not have any Deprecated annotation or comment | t | f | f | .Dead code, 2.The class is annotated as deprecated but it does not have any Deprecated annotation or comment. | data class | 0 | 3132 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 2 | 298 | 3132 |
| 299 | { "response": "YES I found bad smells", "detectedBadSmells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3147 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 1 | 299 | 3147 |
| 299 | YES I found bad smells: -The method name is not descriptive. -The parameter names are not descriptive. -There is no logic or explanation for the code. -The code is not properly formatted or indented. The bad smells are: 1. Poorly named method 2. Poorly named parameters 3. Lack of logic/explanation 4. Poor formatting/indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | Poorly named method2 Poorly named parameters3 Lack of logic/explanation4 Poor formatting/indentation | t | f | f | . Poorly named method2. Poorly named parameters3. Lack of logic/explanation4. Poor formatting/indentation | feature envy | 0 | 3147 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 2 | 299 | 3147 |
| 301 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3155 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 301 | 3155 |
| 301 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 3155 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 301 | 3155 |
| 302 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | long method, data class | t | t | t | long method | 0 | 3165 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 1 | 302 | 3165 | |
| 302 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (method is accessing multiple data from the associated protocol) 3. Redundant comments/documentation (ex: "// Set the list of Cookies on the request") 4. Inconsistent naming convention for methods (ex: "getHeaders", "getCookies", "getExtensions") 5. Deprecated method still present in the interface but explicitly marked as deprecated. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | Long method2 Feature envy (method is accessing multiple data from the associated protocol)3 Redundant comments/documentation (ex: "// Set the list of Cookies on the request")4 Inconsistent naming convention for methods (ex: "getHeaders", "getCookies", "getExtensions")5 Deprecated method still present in the interface but explicitly marked as deprecated | t | f | f | . Long method2. Feature envy (method is accessing multiple data from the associated protocol)3. Redundant comments/documentation (ex: "// Set the list of Cookies on the request")4. Inconsistent naming convention for methods (ex: "getHeaders", "getCookies", "getExtensions")5. Deprecated method still present in the interface but explicitly marked as deprecated. | data class | 0 | 3165 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 302 | 3165 |
| 303 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3173 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 1 | 303 | 3173 |
| 303 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | Long method | t | f | f | .Long method | feature envy | 0 | 3173 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 2 | 303 | 3173 |
| 304 | YES I found bad smells the bad smells are: 1.Magic number, 2.Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Magic number, 2Duplicate code | t | f | f | .Magic number, 2.Duplicate code | data class | 0 | 3183 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 2 | 304 | 3183 |
| 305 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3185 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 305 | 3185 |
| 306 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final static class Builder { private Supplier initialValue; private UnaryOperator splitOperator = null; private BinaryOperator mergeOperator = null; private Builder() { } public Builder initialValue(final Supplier initialValue) { this.initialValue = initialValue; return this; } public Builder splitOperator(final UnaryOperator splitOperator) { this.splitOperator = splitOperator; return this; } public Builder mergeOperator(final BinaryOperator mergeOperator) { this.mergeOperator = mergeOperator; return this; } public SackStrategy create() { return new SackStrategy(this.initialValue, this.splitOperator, this.mergeOperator); } } |
data class | data class | t | t | t | 0 | 3195 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/SackStrategy.java/#L58-L85 | 1 | 306 | 3195 | ||
| 306 | " YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final static class Builder { private Supplier initialValue; private UnaryOperator splitOperator = null; private BinaryOperator mergeOperator = null; private Builder() { } public Builder initialValue(final Supplier initialValue) { this.initialValue = initialValue; return this; } public Builder splitOperator(final UnaryOperator splitOperator) { this.splitOperator = splitOperator; return this; } public Builder mergeOperator(final BinaryOperator mergeOperator) { this.mergeOperator = mergeOperator; return this; } public SackStrategy create() { return new SackStrategy(this.initialValue, this.splitOperator, this.mergeOperator); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3195 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/SackStrategy.java/#L58-L85 | 2 | 306 | 3195 |
| 307 | { "message": "YES, I found bad smells", "detected_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int getDVDTotalTitles() { if (bdp != null) return bdp.getNumTitles(); return 0; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 3199 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/MiniPlayer.java/#L2879-L2884 | 1 | 307 | 3199 | |
| 307 | YES, I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int getDVDTotalTitles() { if (bdp != null) return bdp.getNumTitles(); return 0; } |
feature envy | Long Method | t | f | f | . Long Method | feature envy | 0 | 3199 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/MiniPlayer.java/#L2879-L2884 | 2 | 307 | 3199 |
| 308 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RewriteLoadBalancerClient implements LoadBalancerClient { private static final Logger _log = LoggerFactory.getLogger(TrackerClient.class); private final String _serviceName; private final URI _uri; private final RewriteClient _client; public RewriteLoadBalancerClient(String serviceName, URI uri, TransportClient client) { _serviceName = serviceName; _uri = uri; _client = new RewriteClient(client, new D2URIRewriter(uri)); debug(_log, "created rewrite client: ", this); } @Override public void restRequest(RestRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.restRequest(request, requestContext, wireAttrs, callback); } @Override public void streamRequest(StreamRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.streamRequest(request, requestContext, wireAttrs, callback); } @Override public void shutdown(Callback callback) { _client.shutdown(callback); } @Deprecated public TransportClient getWrappedClient() { return _client; } public TransportClient getDecoratedClient() { return _client; } @Override public URI getUri() { return _uri; } public String getServiceName() { return _serviceName; } @Override public String toString() { return "RewriteLoadBalancerClient [_serviceName=" + _serviceName + ", _uri=" + _uri + ", _wrappedClient=" + _client + "]"; } } |
data class | data class | t | t | t | 0 | 3201 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/d2/src/main/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClient.java/#L41-L111 | 1 | 308 | 3201 | ||
| 308 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RewriteLoadBalancerClient implements LoadBalancerClient { private static final Logger _log = LoggerFactory.getLogger(TrackerClient.class); private final String _serviceName; private final URI _uri; private final RewriteClient _client; public RewriteLoadBalancerClient(String serviceName, URI uri, TransportClient client) { _serviceName = serviceName; _uri = uri; _client = new RewriteClient(client, new D2URIRewriter(uri)); debug(_log, "created rewrite client: ", this); } @Override public void restRequest(RestRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.restRequest(request, requestContext, wireAttrs, callback); } @Override public void streamRequest(StreamRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.streamRequest(request, requestContext, wireAttrs, callback); } @Override public void shutdown(Callback callback) { _client.shutdown(callback); } @Deprecated public TransportClient getWrappedClient() { return _client; } public TransportClient getDecoratedClient() { return _client; } @Override public URI getUri() { return _uri; } public String getServiceName() { return _serviceName; } @Override public String toString() { return "RewriteLoadBalancerClient [_serviceName=" + _serviceName + ", _uri=" + _uri + ", _wrappedClient=" + _client + "]"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3201 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/d2/src/main/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClient.java/#L41-L111 | 2 | 308 | 3201 |
| 309 | Yes I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 3204 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 2 | 309 | 3204 | |
| 310 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 3205 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 2 | 310 | 3205 | |
| 310 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3205 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 1 | 310 | 3205 |
| 311 | YES, I found bad smellsThe bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getTraceback() { return traceback; } |
feature envy | Feature envy | t | f | t | 0 | 3207 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-jupyter/src/main/java/org/apache/zeppelin/jupyter/nbformat/Error.java/#L48-L50 | 2 | 311 | 3207 | ||
| 312 | {"response": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onNodeSelected(TreeNodeElement node, SignalEvent event) { getSelectionModel().setTreeActive(true); selectNode(node.getData(), event, true); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3213 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/tree/Tree.java/#L732-L736 | 1 | 312 | 3213 |
| 312 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onNodeSelected(TreeNodeElement node, SignalEvent event) { getSelectionModel().setTreeActive(true); selectNode(node.getData(), event, true); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 3213 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/tree/Tree.java/#L732-L736 | 2 | 312 | 3213 |
| 313 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void transformKeyReferences(RefTransformer visitor) { configs.forEach(c -> c.transformKeyReferences(visitor)); } |
feature envy | feature envy | t | t | t | 0 | 3219 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/resources/ResTableTypeSpec.java/#L166-L168 | 1 | 313 | 3219 | ||
| 313 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void transformKeyReferences(RefTransformer visitor) { configs.forEach(c -> c.transformKeyReferences(visitor)); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3219 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/resources/ResTableTypeSpec.java/#L166-L168 | 2 | 313 | 3219 | ||
| 314 | Note:YES I found bad smells the bad smells are: 1. Inconsistent indentation and formatting 2. Misleading variable names 3. Unclear hierarchy and purpose of classes and methods 4. Poor encapsulation of the side input feature 5. Possible violation of the Single Responsibility Principle (SRP) by having multiple responsibilities in one class 6. Potential feature envy in the setSideInput() method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | Inconsistent indentation and formatting2 Misleading variable names3 Unclear hierarchy and purpose of classes and methods4 Poor encapsulation of the side input feature5 Possible violation of the Single Responsibility Principle (SRP) by having multiple responsibilities in one class6 Potential feature envy in the setSideInput() method | t | f | f | . Inconsistent indentation and formatting2. Misleading variable names3. Unclear hierarchy and purpose of classes and methods4. Poor encapsulation of the side input feature5. Possible violation of the Single Responsibility Principle (SRP) by having multiple responsibilities in one class6. Potential feature envy in the setSideInput() method | data class | 0 | 3227 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 2 | 314 | 3227 |
| 314 | { "output": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | data class, long method | t | t | t | long method | 0 | 3227 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 1 | 314 | 3227 | |
| 315 | {"response":"YES I found bad smells","bad smells are":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3235 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 1 | 315 | 3235 |
| 315 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3235 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 2 | 315 | 3235 |
| 316 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | feature envy | t | t | t | 0 | 3247 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 1 | 316 | 3247 | ||
| 316 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | Feature envy | t | f | t | 0 | 3247 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 2 | 316 | 3247 | ||
| 317 | { "output": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | the bad smells are: long method | t | t | f | the bad smells are: long method | data class | 0 | 3255 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 1 | 317 | 3255 |
| 317 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 3255 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 2 | 317 | 3255 |
| 318 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | long method | t | t | t | 0 | 3262 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 1 | 318 | 3262 | ||
| 318 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3262 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 2 | 318 | 3262 | ||
| 320 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3293 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 1 | 320 | 3293 |
| 320 | YES I found bad smells the bad smells are: 1. Feature envy - this class appears to be too focused on a specific type of data (i.e. columns and families) and may not be reusable or extensible for other purposes. 2. Long method - the constructor and equals() method are relatively long, potentially indicating that this class is trying to handle multiple responsibilities. 3. Lack of encapsulation - the fields regionInfo and familySet are public, which could lead to unintended data manipulation. 4. Possible null pointer exception - the equals() method does not check for null values, which could result in an error if a null value is passed in as an argument. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | Feature envy - this class appears to be too focused on a specific type of data (ie columns and families) and may not be reusable or extensible for other purposes2 Long method - the constructor and equals() method are relatively long, potentially indicating that this class is trying to handle multiple responsibilities3 Lack of encapsulation - the fields regionInfo and familySet are public, which could lead to unintended data manipulation4 Possible null pointer exception - the equals() method does not check for null values, which could result in an error if a null value is passed in as an argument | t | f | f | . Feature envy - this class appears to be too focused on a specific type of data (i.e. columns and families) and may not be reusable or extensible for other purposes.2. Long method - the constructor and equals() method are relatively long, potentially indicating that this class is trying to handle multiple responsibilities.3. Lack of encapsulation - the fields regionInfo and familySet are public, which could lead to unintended data manipulation.4. Possible null pointer exception - the equals() method does not check for null values, which could result in an error if a null value is passed in as an argument. | data class | 0 | 3293 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 2 | 320 | 3293 |
| 322 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public MessageReference copy(final Queue queue) { return new MessageReferenceImpl(this, queue); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3309 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java/#L137-L140 | 1 | 322 | 3309 |
| 322 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public MessageReference copy(final Queue queue) { return new MessageReferenceImpl(this, queue); } |
feature envy | Feature envy | t | f | t | 0 | 3309 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java/#L137-L140 | 2 | 322 | 3309 | ||
| 324 | //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup_1() { return cGroup_1; } //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1_0() { return cGroup_1_0; } //=> ({BinaryLogicalExpression.lhs=current} public Group getGroup_1_0_0() { return cGroup_1_0_0; } YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | () { return cGroup_ | t | f | f | () { return cGroup_ | data class | 0 | 3343 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 324 | 3343 |
| 324 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | data class, long method | t | t | t | long method | 0 | 3343 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 324 | 3343 | |
| 326 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | 1. data class | t | t | t | 0 | 3376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 1 | 326 | 3376 | ||
| 326 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 2 | 326 | 3376 |
| 327 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | data class | t | t | t | 0 | 3381 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 1 | 327 | 3381 | ||
| 327 | YES I found bad smells the bad smells are: 1. Long method 2. No cohesion | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | Long method 2 No cohesion | t | f | f | . Long method 2. No cohesion | data class | 0 | 3381 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 2 | 327 | 3381 |
| 328 | YES, I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3385 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 2 | 328 | 3385 |
| 329 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | data class | t | t | t | 0 | 3387 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 1 | 329 | 3387 | ||
| 329 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3387 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 2 | 329 | 3387 |
| 331 | { "response": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Expression setUpper(Bound newUpper) { upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive); return this; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 3397 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/index/sasi/plan/Expression.java/#L127-L131 | 1 | 331 | 3397 |
| 331 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Expression setUpper(Bound newUpper) { upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive); return this; } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 3397 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/index/sasi/plan/Expression.java/#L127-L131 | 2 | 331 | 3397 |
| 332 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract static class Builder> { protected abstract T self(); protected Long id; protected String name; protected String description; /** * @see Option#getId() */ public T id(Long id) { this.id = id; return self(); } /** * @see Option#getName() */ public T name(String name) { this.name = name; return self(); } /** * @see Option#getDescription() */ public T description(String description) { this.description = description; return self(); } public Option build() { return new Option(id, name, description); } public T fromOption(Option in) { return this .id(in.getId()) .name(in.getName()) .description(in.getDescription()); } } |
data class | long method | t | t | f | long method | data class | 0 | 3402 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Option.java/#L48-L89 | 1 | 332 | 3402 |
| 332 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract static class Builder> { protected abstract T self(); protected Long id; protected String name; protected String description; /** * @see Option#getId() */ public T id(Long id) { this.id = id; return self(); } /** * @see Option#getName() */ public T name(String name) { this.name = name; return self(); } /** * @see Option#getDescription() */ public T description(String description) { this.description = description; return self(); } public Option build() { return new Option(id, name, description); } public T fromOption(Option in) { return this .id(in.getId()) .name(in.getName()) .description(in.getDescription()); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 3402 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Option.java/#L48-L89 | 2 | 332 | 3402 |
| 333 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static boolean checkExplicitUserPassword(ManagementContext mgmt, String user, String password) { BrooklynProperties properties = ((ManagementContextInternal)mgmt).getBrooklynProperties(); String expectedPassword = properties.getConfig(BrooklynWebConfig.PASSWORD_FOR_USER(user)); String salt = properties.getConfig(BrooklynWebConfig.SALT_FOR_USER(user)); String expectedSha256 = properties.getConfig(BrooklynWebConfig.SHA256_FOR_USER(user)); return checkPassword(password, expectedPassword, expectedSha256, salt); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 3421 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/rest/rest-server/src/main/java/org/apache/brooklyn/rest/security/provider/ExplicitUsersSecurityProvider.java/#L94-L101 | 1 | 333 | 3421 |
| 333 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static boolean checkExplicitUserPassword(ManagementContext mgmt, String user, String password) { BrooklynProperties properties = ((ManagementContextInternal)mgmt).getBrooklynProperties(); String expectedPassword = properties.getConfig(BrooklynWebConfig.PASSWORD_FOR_USER(user)); String salt = properties.getConfig(BrooklynWebConfig.SALT_FOR_USER(user)); String expectedSha256 = properties.getConfig(BrooklynWebConfig.SHA256_FOR_USER(user)); return checkPassword(password, expectedPassword, expectedSha256, salt); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 3421 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/rest/rest-server/src/main/java/org/apache/brooklyn/rest/security/provider/ExplicitUsersSecurityProvider.java/#L94-L101 | 2 | 333 | 3421 | ||
| 335 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method | t | t | t | 0 | 3439 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 335 | 3439 | ||
| 335 | YES I found bad smells The bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method 2 Feature Envy | t | f | t | 0 | 3439 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 335 | 3439 | ||
| 336 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | 1. long method | t | t | t | 0 | 3447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 336 | 3447 | ||
| 336 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Inconsistent Indentation 5. Primitive Obsession 6. Magic Numbers 7. Bloated code with unnecessary if-else statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long Method 2 Feature Envy 3 Duplicate Code 4 Inconsistent Indentation 5 Primitive Obsession 6 Magic Numbers 7 Bloated code with unnecessary if-else statements | t | f | t | 0 | 3447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 336 | 3447 | ||
| 337 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | data class | t | t | t | 0 | 3472 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 337 | 3472 | ||
| 337 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicated code 3. Inconsistent spacing and indentation 4. Unused imports 5. Unused variables 6. Magic numbers/constants without explanation 7. Use of raw types without type argument 8. Missing comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | Long method2 Duplicated code3 Inconsistent spacing and indentation4 Unused imports5 Unused variables6 Magic numbers/constants without explanation7 Use of raw types without type argument8 Missing comments/documentation | t | f | f | . Long method2. Duplicated code3. Inconsistent spacing and indentation4. Unused imports5. Unused variables6. Magic numbers/constants without explanation7. Use of raw types without type argument8. Missing comments/documentation | data class | 0 | 3472 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 337 | 3472 |
| 338 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy (getters and setters) 3. Primitive obsession (declaring lists and hashmaps instead of creating custom objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | Long method2 Feature envy (getters and setters)3 Primitive obsession (declaring lists and hashmaps instead of creating custom objects) | t | f | f | . Long method2. Feature envy (getters and setters)3. Primitive obsession (declaring lists and hashmaps instead of creating custom objects) | data class | 0 | 3483 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 2 | 338 | 3483 |
| 342 | { "error": "You haven't provided any input for me to check for code smells." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Not specified | f | f | f | false | 0 | 3502 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 342 | 3502 | |
| 342 | YES I found bad smells: 1. Long method 2. Feature envy 3. Data class violation 4. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy3 Data class violation4 Primitive obsession | t | f | t | 0 | 3502 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 342 | 3502 | ||
| 343 | YES I found bad smells the bad smells are: 1. Class is too small 2. Useless parentheses 3. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NamespaceFilter extends XMLFilterImpl { private static final InputSource EMPTY_INPUT_SOURCE = new InputSource(new ByteArrayInputStream(new byte[0])); public NamespaceFilter(XMLReader xmlReader) { super(xmlReader); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return EMPTY_INPUT_SOURCE; } } |
data class | Class is too small2 Useless parentheses3 Long method | t | f | f | . Class is too small2. Useless parentheses3. Long method | data class | 0 | 3503 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/sun/JaxbSun.java/#L96-L106 | 2 | 343 | 3503 |
| 344 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | f | f | f | data class | 0 | 3516 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 344 | 3516 | ||
| 344 | {"response": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 3516 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 344 | 3516 |
| 345 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 3519 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 1 | 345 | 3519 |
| 345 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3519 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 2 | 345 | 3519 | ||
| 346 | no NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | f | f | f | long method | 0 | 3525 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 346 | 3525 | ||
| 346 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3525 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 346 | 3525 | |
| 347 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long method | t | f | t | 0 | 3549 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 347 | 3549 | ||
| 350 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3597 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 2 | 350 | 3597 |
| 351 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | 1. long method | t | t | t | 0 | 3600 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 351 | 3600 | ||
| 351 | YES I found bad smells The bad smells are:1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3600 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 351 | 3600 | ||
| 352 | {"message": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DBMsgConstants { public static final int MAX_BODY_SIZE = 64 * 1024 * 1024; //64KB } |
data class | f | f | f | data class | 0 | 3605 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/constant/DBMsgConstants.java/#L20-L22 | 1 | 352 | 3605 | ||
| 352 | Yes I found bad smells The bad smells are: 1. Magic numbers 2. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DBMsgConstants { public static final int MAX_BODY_SIZE = 64 * 1024 * 1024; //64KB } |
data class | Magic numbers2 Inconsistent naming conventions | t | f | f | . Magic numbers2. Inconsistent naming conventions | data class | 0 | 3605 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/constant/DBMsgConstants.java/#L20-L22 | 2 | 352 | 3605 |
| 353 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | long method | t | t | t | 0 | 3634 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 353 | 3634 | ||
| 353 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Duplicated code, 4.Nested try/catch blocks, 5.Unused parameters, 6.Inconsistent naming conventions, 7.Hardcoded class names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2Magic numbers, 3Duplicated code, 4Nested try/catch blocks, 5Unused parameters, 6Inconsistent naming conventions, 7Hardcoded class names | t | f | t | 2.Magic numbers, 3.Duplicated code, 4.Nested try/catch blocks, 5.Unused parameters, 6.Inconsistent naming conventions, 7.Hardcoded class names | 0 | 3634 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 353 | 3634 | |
| 355 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | data class | t | t | t | 0 | 3668 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 1 | 355 | 3668 | ||
| 355 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 3668 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 2 | 355 | 3668 |
| 356 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value public class Release { private final String id; private final ProjectKey projectKey; private final String name; private final String description; private final LocalDate date; } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3676 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/model/Release.java/#L25-L33 | 2 | 356 | 3676 |
| 357 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ConfigFilePropertySource extends FilePropertySource { private IFile file; public ConfigFilePropertySource(IFile file) { super(file); this.file = file; } @Override public String toString() { return file.getFullPath().toString(); } } |
data class | f | f | f | data class | 0 | 3677 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.beans.ui/src/org/springframework/ide/eclipse/beans/ui/model/properties/ChildBeanProperties.java/#L154-L166 | 1 | 357 | 3677 | ||
| 357 | YES I found bad smells The bad smells are: 1. Long method (toString method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ConfigFilePropertySource extends FilePropertySource { private IFile file; public ConfigFilePropertySource(IFile file) { super(file); this.file = file; } @Override public String toString() { return file.getFullPath().toString(); } } |
data class | Long method (toString method) | t | f | f | . Long method (toString method) | data class | 0 | 3677 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.beans.ui/src/org/springframework/ide/eclipse/beans/ui/model/properties/ChildBeanProperties.java/#L154-L166 | 2 | 357 | 3677 |
| 359 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3692 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 1 | 359 | 3692 |
| 359 | YES I found bad smells the bad smells are: 1. Long method 2. Repetitive code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
feature envy | Long method 2 Repetitive code 3 Feature envy | t | f | t | 0 | 3692 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 2 | 359 | 3692 | ||
| 360 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | data class | t | t | t | 0 | 3696 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 1 | 360 | 3696 | ||
| 360 | YES I found bad smells the bad smells are: 1. Long method, 2. Data class, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | Long method, 2 Data class, 3 Feature envy | t | f | t | . Long method, 3. Feature envy | 0 | 3696 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 2 | 360 | 3696 | |
| 361 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | long method | t | t | t | 0 | 3699 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 361 | 3699 | ||
| 361 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3699 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 361 | 3699 | ||
| 362 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Listener(clustered = false, sync = false) public class InfinispanAsyncLocalEventListener extends InfinispanSyncLocalEventListener { public InfinispanAsyncLocalEventListener(InfinispanConsumer consumer, Set eventTypes) { super(consumer, eventTypes); } } |
data class | data class | t | t | t | 0 | 3707 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/embedded/InfinispanAsyncLocalEventListener.java/#L24-L29 | 1 | 362 | 3707 | ||
| 362 | YES, I found bad smells The bad smells are: 1.Duplicated Code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Listener(clustered = false, sync = false) public class InfinispanAsyncLocalEventListener extends InfinispanSyncLocalEventListener { public InfinispanAsyncLocalEventListener(InfinispanConsumer consumer, Set eventTypes) { super(consumer, eventTypes); } } |
data class | Duplicated Code | t | f | f | .Duplicated Code | data class | 0 | 3707 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/embedded/InfinispanAsyncLocalEventListener.java/#L24-L29 | 2 | 362 | 3707 |
| 366 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 3740 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 366 | 3740 |
| 366 | YES I found bad smells the bad smells are: 1. Long method 2. Method with multiple responsibilities 3. Feature envy 4. Code duplication (the for loop that allocates columns could be extracted into a separate method) 5. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method2 Method with multiple responsibilities3 Feature envy4 Code duplication (the for loop that allocates columns could be extracted into a separate method)5 Lack of comments/documentation | t | f | t | 0 | 3740 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 366 | 3740 | ||
| 367 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 3757 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 2 | 367 | 3757 |
| 368 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3790 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 368 | 3790 |
| 368 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3790 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 368 | 3790 |
| 369 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3819 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 369 | 3819 | |
| 369 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 3819 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 369 | 3819 | ||
| 370 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Class getPropertyEditorClass(final Object bean, final String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyEditorClass(bean, name); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 3845 | https://github.com/apache/commons-beanutils/blob/33a067788f2a414c0b019f8d8974cc455c1982a4/src/main/java/org/apache/commons/beanutils2/PropertyUtils.java/#L458-L464 | 1 | 370 | 3845 |
| 370 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Class getPropertyEditorClass(final Object bean, final String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyEditorClass(bean, name); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 3845 | https://github.com/apache/commons-beanutils/blob/33a067788f2a414c0b019f8d8974cc455c1982a4/src/main/java/org/apache/commons/beanutils2/PropertyUtils.java/#L458-L464 | 2 | 370 | 3845 | ||
| 371 | { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3852 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 1 | 371 | 3852 | |
| 371 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 3852 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 2 | 371 | 3852 | ||
| 372 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | 1. data class | t | t | f | data class | 0 | 3859 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 372 | 3859 | |
| 372 | public static class MyBigIntArrayList { // TODO private BigInteger[] elems = new BigInteger[100]; private int size = 0; public MyBigIntArrayList() { } public void add(BigInteger e) { if (size == elems.length) { BigInteger[] temp = new BigInteger[size + 10]; for (int i = 0; i < size; i++) { temp[i] = elems[i]; } elems = temp; } else elems[size] = e; } YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy: The "count" variable in the "Value" class is not being used and should be removed. The "elems" array in the "MyBigIntArrayList" class should be declared as final since it is never reassigned. The "add" method in the "MyBigIntArrayList" class can be shortened and simplified. The "temp" variable in the "add" method is unnecessary and can be removed. Magic numbers are present in the code (100 and 10) and should be replaced with named constants. The name of the "add" method is not clear and should be renamed to "addElement". | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | 00]; privateint size = 0; public MyBigIntArrayList() { } public void add(BigInteger e) { if (size == elemslength) { BigInteger[] temp = new BigInteger[size + | t | f | f | 00]; privateint size = 0; public MyBigIntArrayList() { } public void add(BigInteger e) { if (size == elems.length) { BigInteger[] temp = new BigInteger[size + | data class | 0 | 3859 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 372 | 3859 |
| 374 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | long method | t | t | t | 0 | 3864 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 374 | 3864 | ||
| 374 | YES I found bad smells, the bad smells are: 1. Long method, 2. Magic strings, 3. Multiple statements per line, 4. Duplicate code, 5. Non-descriptive variable names, 6. Hard-coded values, 7. Poorly structured code, 8. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method, 2 Magic strings, 3 Multiple statements per line, 4 Duplicate code, 5 Non-descriptive variable names, 6 Hard-coded values, 7 Poorly structured code, 8 Feature envy | t | f | t | 2. Magic strings, 3. Multiple statements per line, 4. Duplicate code, 5. Non-descriptive variable names, 6. Hard-coded values, 7. Poorly structured code, 8. Feature envy. | 0 | 3864 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 374 | 3864 | |
| 376 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override int recursionUnsafeHashCode() { return System.identityHashCode(this); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3877 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/AllType.java/#L112-L115 | 1 | 376 | 3877 |
| 376 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override int recursionUnsafeHashCode() { return System.identityHashCode(this); } |
feature envy | Feature envy | t | f | t | 0 | 3877 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/AllType.java/#L112-L115 | 2 | 376 | 3877 | ||
| 377 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class JsonObjects { private static final Jsonb JSON = JsonbBuilder.create(); private JsonObjects() { } static List getColumns(JsonObject jsonObject) { Map map = JSON.fromJson(jsonObject.toString(), Map.class); return Columns.of(map); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3896 | https://github.com/eclipse/jnosql/blob/9f03fa6ffe2dd4b538f7dbce424649aa4e484657/communication/diana-column/src/main/java/org/jnosql/diana/api/column/query/JsonObjects.java/#L28-L40 | 2 | 377 | 3896 |
| 378 | { "message": "YES I found bad smells", "detectedBadSmells": [ "Long Method", "Feature Envy" ], "theBadSmellsAre": "1. Long Method, 2. Feature Envy" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
feature envy | Incoherent response format, very different from what was expected. | f | f | f | false | 0 | 3904 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 378 | 3904 | |
| 378 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Use of switch statement instead of alternative strategies | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
feature envy | Long method2 Feature envy3 Duplicate code4 Use of switch statement instead of alternative strategies | t | f | t | 0 | 3904 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 378 | 3904 | ||
| 379 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | 1. long method | t | t | f | long method | 0 | 3905 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 379 | 3905 | |
| 379 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Switch statement 4. Possible lack of comparison strategy for different cases 5. Use of instanceof operator 6. Use of type-unsafe comparison between different types (numbers and strings) 7. Lack of proper comments/documentation 8. Unclear and potentially misleading variable names such as "o1" and "o2" 9. Potential for code duplication due to nested if/else statements 10. Use of raw type Collection instead of parametrized type | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long method2 Feature envy3 Switch statement4 Possible lack of comparison strategy for different cases5 Use of instanceof operator6 Use of type-unsafe comparison between different types (numbers and strings)7 Lack of proper comments/documentation8 Unclear and potentially misleading variable names such as "o | t | f | t | 0 | 3905 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 379 | 3905 | ||
| 380 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | 1: long method | t | t | f | 1: long method | data class | 0 | 3907 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 1 | 380 | 3907 |
| 380 | YES I found bad smells the bad smells are: 1. Feature envy 2. Feature envy 3. Feature envy 4. Feature envy 5. Feature envy 6. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | Feature envy2 Feature envy3 Feature envy4 Feature envy5 Feature envy6 Long method | t | f | f | . Feature envy2. Feature envy3. Feature envy4. Feature envy5. Feature envy6. Long method | data class | 0 | 3907 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 2 | 380 | 3907 |
| 381 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean isVisible(final IStructuredSelection selection) { final ChangeItem[] changes = (ChangeItem[]) SelectionUtils.selectionToArray(getSelection(), ChangeItem.class); // Enable for any delete for (final ChangeItem change : changes) { if (change.getChangeType().contains(ChangeType.DELETE)) { return true; } } return false; } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 3908 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/dialogs/vc/candidates/RestoreAction.java/#L55-L66 | 1 | 381 | 3908 |
| 381 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean isVisible(final IStructuredSelection selection) { final ChangeItem[] changes = (ChangeItem[]) SelectionUtils.selectionToArray(getSelection(), ChangeItem.class); // Enable for any delete for (final ChangeItem change : changes) { if (change.getChangeType().contains(ChangeType.DELETE)) { return true; } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3908 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/dialogs/vc/candidates/RestoreAction.java/#L55-L66 | 2 | 381 | 3908 | ||
| 382 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 3913 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 382 | 3913 |
| 382 | YES I found bad smells the bad smells are: 1.Long method, 2. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Long method, 2 Shotgun surgery | t | f | f | .Long method, 2. Shotgun surgery | data class | 0 | 3913 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 382 | 3913 |
| 383 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | 1. long method | t | t | f | long method | 0 | 3920 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 383 | 3920 | |
| 383 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3920 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 383 | 3920 | ||
| 384 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3921 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 384 | 3921 |
| 384 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3921 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 384 | 3921 | ||
| 385 | { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | data class, long method | t | t | t | long method | 0 | 3938 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 1 | 385 | 3938 | |
| 385 | YES, I found bad smells the bad smells are: 1. Long method 2. Long class 3. Shotgun surgery 4. Feature envy 5. Data class 6. God class 7. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | Long method2 Long class3 Shotgun surgery4 Feature envy 5 Data class 6 God class7 Lazy class | t | f | t | 0 | 3938 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 2 | 385 | 3938 | ||
| 387 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3944 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 387 | 3944 | |
| 387 | YES I found bad smells The bad smells are: 1. Long Method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long Method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 3944 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 387 | 3944 | |
| 388 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 3945 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 388 | 3945 | |
| 388 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Magic strings, 4.Hardcoded values, 5.Deeply nested code, 6.Feature envy, 7.Inappropriate coupling, 8.Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | Long method, 2Magic numbers, 3Magic strings, 4Hardcoded values, 5Deeply nested code, 6Feature envy, 7Inappropriate coupling, 8Inconsistent naming conventions | t | f | t | .Long method, 2.Magic numbers, 3.Magic strings, 4.Hardcoded values, 5.Deeply nested code, 7.Inappropriate coupling, 8.Inconsistent naming conventions. | 0 | 3945 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 388 | 3945 | |
| 391 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Duplicate code", "Deeply nested code", "Feature envy", "Data class", "Shotgun surgery" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method, duplicate code, deeply nested code, feature envy, data class, shotgun surgery | t | t | f | long method, duplicate code, deeply nested code, feature envy, shotgun surgery | data class | 0 | 3964 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 391 | 3964 |
| 391 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method | t | t | f | long method | data class | 0 | 3964 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 391 | 3964 |
| 393 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | long method | t | t | t | 0 | 3969 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 1 | 393 | 3969 | ||
| 393 | YES I found bad smells the bad smells are: 1.Duplicated Code 2.Magic Number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Duplicated Code2Magic Number | t | f | f | .Duplicated Code2.Magic Number | long method | 0 | 3969 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 2 | 393 | 3969 |
| 394 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method | t | t | t | 0 | 3978 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 1 | 394 | 3978 | ||
| 394 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Redundant code, 4. Complicated control flow, 5. Code duplication, 6. Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method,2 Feature envy,3 Redundant code,4 Complicated control flow,5 Code duplication,6 Poor exception handling | t | f | t | 2. Feature envy, 3. Redundant code, 4. Complicated control flow, 5. Code duplication, 6. Poor exception handling. | 0 | 3978 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 2 | 394 | 3978 | |
| 396 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | data class, long method | t | t | t | long method | 0 | 4035 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 1 | 396 | 4035 | |
| 396 | YES I found bad smells the bad smells are: 1. Unused constructor 2. Poorly named variables (e.g. Tuple, Mapping) 3. Potential Feature Envy (accessing tuple and mapping properties outside of the Cause class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | Unused constructor2 Poorly named variables (eg Tuple, Mapping)3 Potential Feature Envy (accessing tuple and mapping properties outside of the Cause class) | t | f | f | . Unused constructor2. Poorly named variables (e.g. Tuple, Mapping)3. Potential Feature Envy (accessing tuple and mapping properties outside of the Cause class) | data class | 0 | 4035 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 2 | 396 | 4035 |
| 397 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 4060 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 1 | 397 | 4060 |
| 397 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | f | f | f | feature envy | 0 | 4060 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 2 | 397 | 4060 | ||
| 398 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | data class | t | t | t | 0 | 4066 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 1 | 398 | 4066 | ||
| 398 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 4066 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 2 | 398 | 4066 |
| 399 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface XtypePackage extends EPackage { /** * The package name. * * * @generated */ String eNAME = "xtype"; /** * The package namespace URI. * * * @generated */ String eNS_URI = "http://www.eclipse.org/xtext/xbase/Xtype"; /** * The package namespace name. * * * @generated */ String eNS_PREFIX = "xtype"; /** * The singleton instance of the package. * * * @generated */ XtypePackage eINSTANCE = org.eclipse.xtext.xtype.impl.XtypePackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ int XFUNCTION_TYPE_REF = 0; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Param Types' containment reference list. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__PARAM_TYPES = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The feature id for the 'Return Type' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__RETURN_TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The feature id for the 'Type' reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 2; /** * The feature id for the 'Instance Context' attribute. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 3; /** * The number of structural features of the 'XFunction Type Ref' class. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ int XCOMPUTED_TYPE_REFERENCE = 1; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Type Provider' attribute. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The number of structural features of the 'XComputed Type Reference' class. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ int XIMPORT_SECTION = 2; /** * The feature id for the 'Import Declarations' containment reference list. * * * @generated * @ordered */ int XIMPORT_SECTION__IMPORT_DECLARATIONS = 0; /** * The number of structural features of the 'XImport Section' class. * * * @generated * @ordered */ int XIMPORT_SECTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ int XIMPORT_DECLARATION = 3; /** * The feature id for the 'Wildcard' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__WILDCARD = 0; /** * The feature id for the 'Extension' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__EXTENSION = 1; /** * The feature id for the 'Static' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__STATIC = 2; /** * The feature id for the 'Imported Type' reference. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_TYPE = 3; /** * The feature id for the 'Member Name' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__MEMBER_NAME = 4; /** * The feature id for the 'Imported Namespace' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_NAMESPACE = 5; /** * The number of structural features of the 'XImport Declaration' class. * * * @generated * @ordered */ int XIMPORT_DECLARATION_FEATURE_COUNT = 6; /** * The meta object id for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ int IJVM_TYPE_REFERENCE_PROVIDER = 4; /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XFunctionTypeRef XFunction Type Ref}'. * * * @return the meta object for class 'XFunction Type Ref'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef * @generated */ EClass getXFunctionTypeRef(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes Param Types}'. * * * @return the meta object for the containment reference list 'Param Types'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ParamTypes(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType Return Type}'. * * * @return the meta object for the containment reference 'Return Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ReturnType(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getType Type}'. * * * @return the meta object for the reference 'Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_Type(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext Instance Context}'. * * * @return the meta object for the attribute 'Instance Context'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext() * @see #getXFunctionTypeRef() * @generated */ EAttribute getXFunctionTypeRef_InstanceContext(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XComputedTypeReference XComputed Type Reference}'. * * * @return the meta object for class 'XComputed Type Reference'. * @see org.eclipse.xtext.xtype.XComputedTypeReference * @generated */ EClass getXComputedTypeReference(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider Type Provider}'. * * * @return the meta object for the attribute 'Type Provider'. * @see org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider() * @see #getXComputedTypeReference() * @generated */ EAttribute getXComputedTypeReference_TypeProvider(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportSection XImport Section}'. * * * @return the meta object for class 'XImport Section'. * @see org.eclipse.xtext.xtype.XImportSection * @generated */ EClass getXImportSection(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XImportSection#getImportDeclarations Import Declarations}'. * * * @return the meta object for the containment reference list 'Import Declarations'. * @see org.eclipse.xtext.xtype.XImportSection#getImportDeclarations() * @see #getXImportSection() * @generated */ EReference getXImportSection_ImportDeclarations(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportDeclaration XImport Declaration}'. * * * @return the meta object for class 'XImport Declaration'. * @see org.eclipse.xtext.xtype.XImportDeclaration * @generated */ EClass getXImportDeclaration(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isWildcard Wildcard}'. * * * @return the meta object for the attribute 'Wildcard'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isWildcard() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Wildcard(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isExtension Extension}'. * * * @return the meta object for the attribute 'Extension'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isExtension() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Extension(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isStatic Static}'. * * * @return the meta object for the attribute 'Static'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isStatic() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Static(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedType Imported Type}'. * * * @return the meta object for the reference 'Imported Type'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedType() * @see #getXImportDeclaration() * @generated */ EReference getXImportDeclaration_ImportedType(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getMemberName Member Name}'. * * * @return the meta object for the attribute 'Member Name'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getMemberName() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_MemberName(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace Imported Namespace}'. * * * @return the meta object for the attribute 'Imported Namespace'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_ImportedNamespace(); /** * Returns the meta object for data type '{@link org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider IJvm Type Reference Provider}'. * * * @return the meta object for data type 'IJvm Type Reference Provider'. * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @model instanceClass="org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider" serializeable="false" * @generated */ EDataType getIJvmTypeReferenceProvider(); /** * Returns the factory that creates the instances of the model. * * * @return the factory that creates the instances of the model. * @generated */ XtypeFactory getXtypeFactory(); /** * * Defines literals for the meta objects that represent * * each class, * each feature of each class, * each enum, * and each data type * * * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ EClass XFUNCTION_TYPE_REF = eINSTANCE.getXFunctionTypeRef(); /** * The meta object literal for the 'Param Types' containment reference list feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__PARAM_TYPES = eINSTANCE.getXFunctionTypeRef_ParamTypes(); /** * The meta object literal for the 'Return Type' containment reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__RETURN_TYPE = eINSTANCE.getXFunctionTypeRef_ReturnType(); /** * The meta object literal for the 'Type' reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__TYPE = eINSTANCE.getXFunctionTypeRef_Type(); /** * The meta object literal for the 'Instance Context' attribute feature. * * * @generated */ EAttribute XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = eINSTANCE.getXFunctionTypeRef_InstanceContext(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ EClass XCOMPUTED_TYPE_REFERENCE = eINSTANCE.getXComputedTypeReference(); /** * The meta object literal for the 'Type Provider' attribute feature. * * * @generated */ EAttribute XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = eINSTANCE.getXComputedTypeReference_TypeProvider(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ EClass XIMPORT_SECTION = eINSTANCE.getXImportSection(); /** * The meta object literal for the 'Import Declarations' containment reference list feature. * * * @generated */ EReference XIMPORT_SECTION__IMPORT_DECLARATIONS = eINSTANCE.getXImportSection_ImportDeclarations(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ EClass XIMPORT_DECLARATION = eINSTANCE.getXImportDeclaration(); /** * The meta object literal for the 'Wildcard' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__WILDCARD = eINSTANCE.getXImportDeclaration_Wildcard(); /** * The meta object literal for the 'Extension' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__EXTENSION = eINSTANCE.getXImportDeclaration_Extension(); /** * The meta object literal for the 'Static' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__STATIC = eINSTANCE.getXImportDeclaration_Static(); /** * The meta object literal for the 'Imported Type' reference feature. * * * @generated */ EReference XIMPORT_DECLARATION__IMPORTED_TYPE = eINSTANCE.getXImportDeclaration_ImportedType(); /** * The meta object literal for the 'Member Name' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__MEMBER_NAME = eINSTANCE.getXImportDeclaration_MemberName(); /** * The meta object literal for the 'Imported Namespace' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__IMPORTED_NAMESPACE = eINSTANCE.getXImportDeclaration_ImportedNamespace(); /** * The meta object literal for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ EDataType IJVM_TYPE_REFERENCE_PROVIDER = eINSTANCE.getIJvmTypeReferenceProvider(); } } //XtypePackage |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 4069 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xtype/XtypePackage.java/#L38-L639 | 2 | 399 | 4069 |
| 399 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface XtypePackage extends EPackage { /** * The package name. * * * @generated */ String eNAME = "xtype"; /** * The package namespace URI. * * * @generated */ String eNS_URI = "http://www.eclipse.org/xtext/xbase/Xtype"; /** * The package namespace name. * * * @generated */ String eNS_PREFIX = "xtype"; /** * The singleton instance of the package. * * * @generated */ XtypePackage eINSTANCE = org.eclipse.xtext.xtype.impl.XtypePackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ int XFUNCTION_TYPE_REF = 0; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Param Types' containment reference list. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__PARAM_TYPES = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The feature id for the 'Return Type' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__RETURN_TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The feature id for the 'Type' reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 2; /** * The feature id for the 'Instance Context' attribute. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 3; /** * The number of structural features of the 'XFunction Type Ref' class. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ int XCOMPUTED_TYPE_REFERENCE = 1; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Type Provider' attribute. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The number of structural features of the 'XComputed Type Reference' class. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ int XIMPORT_SECTION = 2; /** * The feature id for the 'Import Declarations' containment reference list. * * * @generated * @ordered */ int XIMPORT_SECTION__IMPORT_DECLARATIONS = 0; /** * The number of structural features of the 'XImport Section' class. * * * @generated * @ordered */ int XIMPORT_SECTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ int XIMPORT_DECLARATION = 3; /** * The feature id for the 'Wildcard' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__WILDCARD = 0; /** * The feature id for the 'Extension' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__EXTENSION = 1; /** * The feature id for the 'Static' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__STATIC = 2; /** * The feature id for the 'Imported Type' reference. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_TYPE = 3; /** * The feature id for the 'Member Name' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__MEMBER_NAME = 4; /** * The feature id for the 'Imported Namespace' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_NAMESPACE = 5; /** * The number of structural features of the 'XImport Declaration' class. * * * @generated * @ordered */ int XIMPORT_DECLARATION_FEATURE_COUNT = 6; /** * The meta object id for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ int IJVM_TYPE_REFERENCE_PROVIDER = 4; /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XFunctionTypeRef XFunction Type Ref}'. * * * @return the meta object for class 'XFunction Type Ref'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef * @generated */ EClass getXFunctionTypeRef(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes Param Types}'. * * * @return the meta object for the containment reference list 'Param Types'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ParamTypes(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType Return Type}'. * * * @return the meta object for the containment reference 'Return Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ReturnType(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getType Type}'. * * * @return the meta object for the reference 'Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_Type(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext Instance Context}'. * * * @return the meta object for the attribute 'Instance Context'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext() * @see #getXFunctionTypeRef() * @generated */ EAttribute getXFunctionTypeRef_InstanceContext(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XComputedTypeReference XComputed Type Reference}'. * * * @return the meta object for class 'XComputed Type Reference'. * @see org.eclipse.xtext.xtype.XComputedTypeReference * @generated */ EClass getXComputedTypeReference(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider Type Provider}'. * * * @return the meta object for the attribute 'Type Provider'. * @see org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider() * @see #getXComputedTypeReference() * @generated */ EAttribute getXComputedTypeReference_TypeProvider(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportSection XImport Section}'. * * * @return the meta object for class 'XImport Section'. * @see org.eclipse.xtext.xtype.XImportSection * @generated */ EClass getXImportSection(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XImportSection#getImportDeclarations Import Declarations}'. * * * @return the meta object for the containment reference list 'Import Declarations'. * @see org.eclipse.xtext.xtype.XImportSection#getImportDeclarations() * @see #getXImportSection() * @generated */ EReference getXImportSection_ImportDeclarations(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportDeclaration XImport Declaration}'. * * * @return the meta object for class 'XImport Declaration'. * @see org.eclipse.xtext.xtype.XImportDeclaration * @generated */ EClass getXImportDeclaration(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isWildcard Wildcard}'. * * * @return the meta object for the attribute 'Wildcard'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isWildcard() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Wildcard(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isExtension Extension}'. * * * @return the meta object for the attribute 'Extension'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isExtension() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Extension(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isStatic Static}'. * * * @return the meta object for the attribute 'Static'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isStatic() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Static(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedType Imported Type}'. * * * @return the meta object for the reference 'Imported Type'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedType() * @see #getXImportDeclaration() * @generated */ EReference getXImportDeclaration_ImportedType(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getMemberName Member Name}'. * * * @return the meta object for the attribute 'Member Name'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getMemberName() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_MemberName(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace Imported Namespace}'. * * * @return the meta object for the attribute 'Imported Namespace'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_ImportedNamespace(); /** * Returns the meta object for data type '{@link org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider IJvm Type Reference Provider}'. * * * @return the meta object for data type 'IJvm Type Reference Provider'. * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @model instanceClass="org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider" serializeable="false" * @generated */ EDataType getIJvmTypeReferenceProvider(); /** * Returns the factory that creates the instances of the model. * * * @return the factory that creates the instances of the model. * @generated */ XtypeFactory getXtypeFactory(); /** * * Defines literals for the meta objects that represent * * each class, * each feature of each class, * each enum, * and each data type * * * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ EClass XFUNCTION_TYPE_REF = eINSTANCE.getXFunctionTypeRef(); /** * The meta object literal for the 'Param Types' containment reference list feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__PARAM_TYPES = eINSTANCE.getXFunctionTypeRef_ParamTypes(); /** * The meta object literal for the 'Return Type' containment reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__RETURN_TYPE = eINSTANCE.getXFunctionTypeRef_ReturnType(); /** * The meta object literal for the 'Type' reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__TYPE = eINSTANCE.getXFunctionTypeRef_Type(); /** * The meta object literal for the 'Instance Context' attribute feature. * * * @generated */ EAttribute XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = eINSTANCE.getXFunctionTypeRef_InstanceContext(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ EClass XCOMPUTED_TYPE_REFERENCE = eINSTANCE.getXComputedTypeReference(); /** * The meta object literal for the 'Type Provider' attribute feature. * * * @generated */ EAttribute XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = eINSTANCE.getXComputedTypeReference_TypeProvider(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ EClass XIMPORT_SECTION = eINSTANCE.getXImportSection(); /** * The meta object literal for the 'Import Declarations' containment reference list feature. * * * @generated */ EReference XIMPORT_SECTION__IMPORT_DECLARATIONS = eINSTANCE.getXImportSection_ImportDeclarations(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ EClass XIMPORT_DECLARATION = eINSTANCE.getXImportDeclaration(); /** * The meta object literal for the 'Wildcard' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__WILDCARD = eINSTANCE.getXImportDeclaration_Wildcard(); /** * The meta object literal for the 'Extension' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__EXTENSION = eINSTANCE.getXImportDeclaration_Extension(); /** * The meta object literal for the 'Static' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__STATIC = eINSTANCE.getXImportDeclaration_Static(); /** * The meta object literal for the 'Imported Type' reference feature. * * * @generated */ EReference XIMPORT_DECLARATION__IMPORTED_TYPE = eINSTANCE.getXImportDeclaration_ImportedType(); /** * The meta object literal for the 'Member Name' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__MEMBER_NAME = eINSTANCE.getXImportDeclaration_MemberName(); /** * The meta object literal for the 'Imported Namespace' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__IMPORTED_NAMESPACE = eINSTANCE.getXImportDeclaration_ImportedNamespace(); /** * The meta object literal for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ EDataType IJVM_TYPE_REFERENCE_PROVIDER = eINSTANCE.getIJvmTypeReferenceProvider(); } } //XtypePackage |
data class | data class, long method | t | t | t | long method | 0 | 4069 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xtype/XtypePackage.java/#L38-L639 | 1 | 399 | 4069 | |
| 401 | { "message": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
feature envy | Not specified | f | f | f | false | 0 | 4102 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 401 | 4102 | |
| 401 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 4102 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 401 | 4102 | |
| 402 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | 1. long method | t | t | t | 0 | 4103 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 402 | 4103 | ||
| 402 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4103 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 402 | 4103 | ||
| 403 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | long method | t | t | f | long method | data class | 0 | 4118 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 403 | 4118 |
| 403 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | Magic numbers2 Long method3 Feature envy | t | f | f | . Magic numbers2. Long method3. Feature envy | data class | 0 | 4118 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 403 | 4118 |
| 406 | {"response": "YES, I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void delete(UserInfo user) throws CoreException { JSONObject sites = getSites(user); if (!sites.has(getId())) { //nothing to do, site does not exist return; } sites.remove(getId()); user.setProperty(SiteConfigurationConstants.KEY_SITE_CONFIGURATIONS, sites.toString()); OrionConfiguration.getMetaStore().updateUser(user); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 4144 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/SiteInfo.java/#L150-L159 | 1 | 406 | 4144 |
| 406 | YES, I found bad smells. 1. Feature envy 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void delete(UserInfo user) throws CoreException { JSONObject sites = getSites(user); if (!sites.has(getId())) { //nothing to do, site does not exist return; } sites.remove(getId()); user.setProperty(SiteConfigurationConstants.KEY_SITE_CONFIGURATIONS, sites.toString()); OrionConfiguration.getMetaStore().updateUser(user); } |
feature envy | Feature envy2 Long method | t | f | t | 0 | 4144 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/SiteInfo.java/#L150-L159 | 2 | 406 | 4144 | ||
| 407 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | 1. long method | t | t | f | long method | 0 | 4155 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 1 | 407 | 4155 | |
| 407 | YES, I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long method2 Long parameter list3 Feature envy | t | f | t | 0 | 4155 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 2 | 407 | 4155 | ||
| 408 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | 1. data class | t | t | t | 0 | 4156 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 408 | 4156 | ||
| 408 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4156 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 408 | 4156 |
| 409 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | 1. data class | t | t | t | 0 | 4159 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 1 | 409 | 4159 | ||
| 409 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4159 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 2 | 409 | 4159 |
| 410 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DIRuntimeException extends RuntimeException { private static final long serialVersionUID = 396131653561690312L; /** * Creates new ConfigurationException without detail message. */ public DIRuntimeException() { } /** * Constructs an exception with the specified message with an optional list * of message formatting arguments. Message formatting rules follow * "String.format(..)" conventions. */ public DIRuntimeException(String messageFormat, Object... messageArgs) { super(String.format(messageFormat, messageArgs)); } /** * Constructs an exception wrapping another exception thrown elsewhere. */ public DIRuntimeException(Throwable cause) { super(cause); } public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) { super(String.format(messageFormat, messageArgs), cause); } } |
data class | data class, long method | t | t | t | long method | 0 | 4172 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-di/src/main/java/org/apache/cayenne/di/DIRuntimeException.java/#L26-L55 | 1 | 410 | 4172 | |
| 410 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DIRuntimeException extends RuntimeException { private static final long serialVersionUID = 396131653561690312L; /** * Creates new ConfigurationException without detail message. */ public DIRuntimeException() { } /** * Constructs an exception with the specified message with an optional list * of message formatting arguments. Message formatting rules follow * "String.format(..)" conventions. */ public DIRuntimeException(String messageFormat, Object... messageArgs) { super(String.format(messageFormat, messageArgs)); } /** * Constructs an exception wrapping another exception thrown elsewhere. */ public DIRuntimeException(Throwable cause) { super(cause); } public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) { super(String.format(messageFormat, messageArgs), cause); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4172 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-di/src/main/java/org/apache/cayenne/di/DIRuntimeException.java/#L26-L55 | 2 | 410 | 4172 |
| 411 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Dead code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ParserRule getCollectionTypeIdentifierRule() { return getCollectionTypeIdentifierAccess().getRule(); } |
feature envy | Magic numbers2 Dead code3 Feature envy | t | f | t | 0 | 4212 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L3702-L3704 | 2 | 411 | 4212 | ||
| 412 | { "error": "Input does not match the expected format. Please provide a list of code smells to check for and the Java code to analyze." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | f | f | f | data class | 0 | 4215 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 412 | 4215 | ||
| 412 | YES I found bad smells the bad smells are: 1. Feature envy: The DynRealmMembership class contains methods and properties that primarily operate on and belong to the JPADynRealm and JPAAnyType classes. This indicates that the class may have a high level of dependency on other classes and may not be cohesive. 2. Long method: The class contains several getter and setter methods which are relatively short, but the overall length of the class may be considered long and may benefit from refactoring into smaller, more focused methods. 3. Duplicated code: The checkType() method is repeated in both the setDynRealm() and setAnyType() methods, indicating potential code duplication. 4. Inappropriate naming: The name FIQLCond for the fiql property may not be clear or descriptive enough for other developers to understand its purpose. 5. Lack of encapsulation: The dynRealm, anyType, and fiql properties are all public, allowing direct access and modification by other classes. Encapsulation could improve data integrity. 6. Violation of OCP: The DynRealmMembership class is directly referencing and type-casting the JPADynRealm and JPAAnyType classes, which limits the flexibility to extend or add new types. This violates the open-closed principle. 7. Lack of validation: The setFIQLCond() method does not validate the input before setting the fiql property, potentially allowing invalid values to be set. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Feature envy: The DynRealmMembership class contains methods and properties that primarily operate on and belong to the JPADynRealm and JPAAnyType classes This indicates that the class may have a high level of dependency on other classes and may not be cohesive2 Long method: The class contains several getter and setter methods which are relatively short, but the overall length of the class may be considered long and may benefit from refactoring into smaller, more focused methods3 Duplicated code: The checkType() method is repeated in both the setDynRealm() and setAnyType() methods, indicating potential code duplication4 Inappropriate naming: The name FIQLCond for the fiql property may not be clear or descriptive enough for other developers to understand its purpose5 Lack of encapsulation: The dynRealm, anyType, and fiql properties are all public, allowing direct access and modification by other classes Encapsulation could improve data integrity6 Violation of OCP: The DynRealmMembership class is directly referencing and type-casting the JPADynRealm and JPAAnyType classes, which limits the flexibility to extend or add new types This violates the open-closed principle7 Lack of validation: The setFIQLCond() method does not validate the input before setting the fiql property, potentially allowing invalid values to be set | t | f | f | . Feature envy: The DynRealmMembership class contains methods and properties that primarily operate on and belong to the JPADynRealm and JPAAnyType classes. This indicates that the class may have a high level of dependency on other classes and may not be cohesive.2. Long method: The class contains several getter and setter methods which are relatively short, but the overall length of the class may be considered long and may benefit from refactoring into smaller, more focused methods.3. Duplicated code: The checkType() method is repeated in both the setDynRealm() and setAnyType() methods, indicating potential code duplication.4. Inappropriate naming: The name FIQLCond for the fiql property may not be clear or descriptive enough for other developers to understand its purpose.5. Lack of encapsulation: The dynRealm, anyType, and fiql properties are all public, allowing direct access and modification by other classes. Encapsulation could improve data integrity.6. Violation of OCP: The DynRealmMembership class is directly referencing and type-casting the JPADynRealm and JPAAnyType classes, which limits the flexibility to extend or add new types. This violates the open-closed principle.7. Lack of validation: The setFIQLCond() method does not validate the input before setting the fiql property, potentially allowing invalid values to be set. | data class | 0 | 4215 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 412 | 4215 |
| 413 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OsgiRequirementAdapter implements Requirement { private static final Logger logger = LoggerFactory.getLogger(OsgiRequirementAdapter.class); private final org.osgi.resource.Requirement requirement; public OsgiRequirementAdapter(org.osgi.resource.Requirement requirement) { if (requirement == null) throw new NullPointerException("Missing required parameter: requirement"); this.requirement = requirement; } public String getComment() { return null; } public String getFilter() { return requirement.getDirectives().get(Constants.FILTER_DIRECTIVE); } public String getName() { return NamespaceTranslator.translate(requirement.getNamespace()); } public boolean isExtend() { return false; } public boolean isMultiple() { String multiple = requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE); return Namespace.CARDINALITY_MULTIPLE.equals(multiple); } public boolean isOptional() { String resolution = requirement.getDirectives().get(Constants.RESOLUTION_DIRECTIVE); return Constants.RESOLUTION_OPTIONAL.equals(resolution); } public boolean isSatisfied(Capability capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); boolean result = ResourceHelper.matches(requirement, new FelixCapabilityAdapter(capability, null)); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } } |
data class | data class, long method | t | t | t | long method | 0 | 4217 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiRequirementAdapter.java/#L28-L72 | 1 | 413 | 4217 | |
| 413 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OsgiRequirementAdapter implements Requirement { private static final Logger logger = LoggerFactory.getLogger(OsgiRequirementAdapter.class); private final org.osgi.resource.Requirement requirement; public OsgiRequirementAdapter(org.osgi.resource.Requirement requirement) { if (requirement == null) throw new NullPointerException("Missing required parameter: requirement"); this.requirement = requirement; } public String getComment() { return null; } public String getFilter() { return requirement.getDirectives().get(Constants.FILTER_DIRECTIVE); } public String getName() { return NamespaceTranslator.translate(requirement.getNamespace()); } public boolean isExtend() { return false; } public boolean isMultiple() { String multiple = requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE); return Namespace.CARDINALITY_MULTIPLE.equals(multiple); } public boolean isOptional() { String resolution = requirement.getDirectives().get(Constants.RESOLUTION_DIRECTIVE); return Constants.RESOLUTION_OPTIONAL.equals(resolution); } public boolean isSatisfied(Capability capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); boolean result = ResourceHelper.matches(requirement, new FelixCapabilityAdapter(capability, null)); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4217 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiRequirementAdapter.java/#L28-L72 | 2 | 413 | 4217 |
| 415 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
data class | long method | t | t | f | long method | data class | 0 | 4221 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 1 | 415 | 4221 |
| 415 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4221 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 2 | 415 | 4221 |
| 417 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 4230 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 1 | 417 | 4230 |
| 417 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4230 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 2 | 417 | 4230 |
| 420 | {"message":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
data class | long method, data class | t | t | t | long method | 0 | 4240 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 1 | 420 | 4240 | |
| 420 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 4240 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 2 | 420 | 4240 |
| 422 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4246 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 422 | 4246 |
| 422 | YES I found bad smells" the bad smells are: 1. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | Feature envy | t | f | t | 0 | 4246 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 422 | 4246 | ||
| 423 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | long method, data class | t | t | t | data class | 0 | 4247 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 423 | 4247 | |
| 423 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 4247 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 423 | 4247 | ||
| 424 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 4255 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 1 | 424 | 4255 |
| 424 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 4255 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 2 | 424 | 4255 |
| 425 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 4257 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L245-L247 | 1 | 425 | 4257 |
| 425 | YES I found bad smells the bad smells are: 1.Long method, 2.Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } |
feature envy | Long method, 2Lazy class | t | f | f | .Long method, 2.Lazy class | feature envy | 0 | 4257 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L245-L247 | 2 | 425 | 4257 |
| 426 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object that) { if( !(that instanceof PlanningCoCodingGroup) ) return false; PlanningCoCodingGroup thatgrp = (PlanningCoCodingGroup) that; return Arrays.equals(_colIndexes, thatgrp._colIndexes); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 4264 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/compress/cocode/PlanningCoCodingGroup.java/#L116-L123 | 1 | 426 | 4264 |
| 426 | YES, I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object that) { if( !(that instanceof PlanningCoCodingGroup) ) return false; PlanningCoCodingGroup thatgrp = (PlanningCoCodingGroup) that; return Arrays.equals(_colIndexes, thatgrp._colIndexes); } |
feature envy | Feature envy | t | f | t | 0 | 4264 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/compress/cocode/PlanningCoCodingGroup.java/#L116-L123 | 2 | 426 | 4264 | ||
| 427 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToCollectionConverter(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Collection.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService .canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } |
data class | long method | t | t | f | long method | data class | 0 | 4266 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java/#L37-L94 | 1 | 427 | 4266 |
| 427 | YES I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToCollectionConverter(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Collection.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService .canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 4266 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java/#L37-L94 | 2 | 427 | 4266 |
| 428 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | data class | t | t | t | 0 | 4270 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 1 | 428 | 4270 | ||
| 428 | YES I found bad smells It is difficult to accurately comment on the code without understanding its context and intended purpose. However, here are some potential bad smells that could be present in the code: 1. Long method in equals() method 2. Feature envy in hashCode() and equals() methods, as they are accessing data from a different object (the AvroWrapper instance) rather than their own data. Note: The toString() method is also potentially a feature envy, as it is accessing data from the AvroWrapper instance rather than its own data. However, this could be necessary for the class's intended purpose. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | Long method in equals() method2 Feature envy in hashCode() and equals() methods, as they are accessing data from a different object (the AvroWrapper instance) rather than their own dataNote: The toString() method is also potentially a feature envy, as it is accessing data from the AvroWrapper instance rather than its own data However, this could be necessary for the class's intended purpose | t | f | f | . Long method in equals() method2. Feature envy in hashCode() and equals() methods, as they are accessing data from a different object (the AvroWrapper instance) rather than their own data.Note: The toString() method is also potentially a feature envy, as it is accessing data from the AvroWrapper instance rather than its own data. However, this could be necessary for the class's intended purpose. | data class | 0 | 4270 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 2 | 428 | 4270 |
| 429 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method | t | t | t | 0 | 4276 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 429 | 4276 | ||
| 429 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 4276 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 429 | 4276 | ||
| 430 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4277 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 430 | 4277 |
| 430 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Data clumps, 4. Comments to explain code, 5. Code duplication, 6. Inappropriate coupling, | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | Long method, 2 Feature envy, 3 Data clumps, 4 Comments to explain code, 5 Code duplication, 6 Inappropriate coupling, | t | f | t | . Long method, 3. Data clumps, 4. Comments to explain code, 5. Code duplication, 6. Inappropriate coupling, | 0 | 4277 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 430 | 4277 | |
| 431 | { "response": "YES, I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public byte getByteAt(long index) { return addr.getJByteAt(baseOffset + index); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4279 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/Symbol.java/#L77-L79 | 1 | 431 | 4279 |
| 431 | " YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public byte getByteAt(long index) { return addr.getJByteAt(baseOffset + index); } |
feature envy | Feature envy | t | f | t | 0 | 4279 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/Symbol.java/#L77-L79 | 2 | 431 | 4279 | ||
| 432 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class InvalidStateTransitionException extends Exception { private Enum currentState; private Enum event; public InvalidStateTransitionException(Enum currentState, Enum event) { super("Invalid event: " + event + " at " + currentState); this.currentState = currentState; this.event = event; } public Enum getCurrentState() { return currentState; } public Enum getEvent() { return event; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 4281 | https://github.com/apache/incubator-ambari/blob/bf747346312170834c6beb89a60c8624b47aa288/ambari-server/src/main/java/org/apache/ambari/server/state/fsm/InvalidStateTransitionException.java/#L25-L45 | 2 | 432 | 4281 |
| 435 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
data class | data class, long method | t | t | t | long method | 0 | 4284 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 1 | 435 | 4284 | |
| 435 | YES I found bad smells- 1.Long method, 2.Magic number, 3.Creation method, 4.Feature envy, 5.Long parameter list, 6.Inappropriate intimacy, 7.Missing or unclear JavaDoc, 8.Unnecessary comments, 9.Data clumps, 10.Long nested blocks, 11.Data class, 12. Inappropriate use of variables, 13.Useless override, 14.Switch statement, 15.Message chains, 16.Duplicated code, 17.Missing type declaration, 18.Illegal catch statement, 19.Inefficient return, 20.Large Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
data class | Long method, 2Magic number, 3Creation method, 4Feature envy, 5Long parameter list, 6Inappropriate intimacy, 7Missing or unclear JavaDoc, 8Unnecessary comments, 9Data clumps, | t | f | f | .Long method, 2.Magic number, 3.Creation method, 4.Feature envy, 5.Long parameter list, 6.Inappropriate intimacy, 7.Missing or unclear JavaDoc, 8.Unnecessary comments, 9.Data clumps, | data class | 0 | 4284 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 2 | 435 | 4284 |
| 437 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder(float k1, float b) { this.similarity = new BM25Similarity(k1, b); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 4292 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L78-L80 | 1 | 437 | 4292 |
| 437 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder(float k1, float b) { this.similarity = new BM25Similarity(k1, b); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 4292 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L78-L80 | 2 | 437 | 4292 |
| 439 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | 1. data class | t | t | f | data class | 0 | 4294 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 1 | 439 | 4294 | |
| 439 | YES I found bad smells The bad smells are: 1. Nested class 2. Long method 3. Long class 4. Feature envy 5. Incomplete error handling 6. Duplicate code 7. Magic numbers 8. Poor naming of variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | Nested class 2 Long method 3 Long class 4 Feature envy 5 Incomplete error handling 6 Duplicate code 7 Magic numbers 8 Poor naming of variables and methods | t | f | f | . Nested class 2. Long method 3. Long class 4. Feature envy 5. Incomplete error handling 6. Duplicate code 7. Magic numbers 8. Poor naming of variables and methods | data class | 0 | 4294 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 2 | 439 | 4294 |
| 440 | {"message": "YES I found bad smells", "bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: interface Failover { String PREFIX = HdfsClientConfigKeys.PREFIX + "failover."; String PROXY_PROVIDER_KEY_PREFIX = PREFIX + "proxy.provider"; String MAX_ATTEMPTS_KEY = PREFIX + "max.attempts"; int MAX_ATTEMPTS_DEFAULT = 15; String SLEEPTIME_BASE_KEY = PREFIX + "sleep.base.millis"; int SLEEPTIME_BASE_DEFAULT = 500; String SLEEPTIME_MAX_KEY = PREFIX + "sleep.max.millis"; int SLEEPTIME_MAX_DEFAULT = 15000; String CONNECTION_RETRIES_KEY = PREFIX + "connection.retries"; int CONNECTION_RETRIES_DEFAULT = 0; String CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY = PREFIX + "connection.retries.on.timeouts"; int CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT = 0; String RANDOM_ORDER = PREFIX + "random.order"; boolean RANDOM_ORDER_DEFAULT = false; String RESOLVE_ADDRESS_NEEDED_KEY = PREFIX + "resolve-needed"; boolean RESOLVE_ADDRESS_NEEDED_DEFAULT = false; String RESOLVE_SERVICE_KEY = PREFIX + "resolver.impl"; } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4300 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java/#L274-L294 | 1 | 440 | 4300 |
| 440 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: interface Failover { String PREFIX = HdfsClientConfigKeys.PREFIX + "failover."; String PROXY_PROVIDER_KEY_PREFIX = PREFIX + "proxy.provider"; String MAX_ATTEMPTS_KEY = PREFIX + "max.attempts"; int MAX_ATTEMPTS_DEFAULT = 15; String SLEEPTIME_BASE_KEY = PREFIX + "sleep.base.millis"; int SLEEPTIME_BASE_DEFAULT = 500; String SLEEPTIME_MAX_KEY = PREFIX + "sleep.max.millis"; int SLEEPTIME_MAX_DEFAULT = 15000; String CONNECTION_RETRIES_KEY = PREFIX + "connection.retries"; int CONNECTION_RETRIES_DEFAULT = 0; String CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY = PREFIX + "connection.retries.on.timeouts"; int CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT = 0; String RANDOM_ORDER = PREFIX + "random.order"; boolean RANDOM_ORDER_DEFAULT = false; String RESOLVE_ADDRESS_NEEDED_KEY = PREFIX + "resolve-needed"; boolean RESOLVE_ADDRESS_NEEDED_DEFAULT = false; String RESOLVE_SERVICE_KEY = PREFIX + "resolver.impl"; } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4300 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java/#L274-L294 | 2 | 440 | 4300 |
| 441 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 4302 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 441 | 4302 |
| 441 | YES, I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Inconsistent naming conventions (e.g. type, Type) 5. Inconsistent spacing/tabs 6. Mixing of responsibilities (e.g. converting types, analyzing type) 7. Use of instanceof 8. Complex nested conditionals 9. Magic numbers/strings (e.g. "Array", "Map") 10. Dependency on external classes (e.g. Primitives) 11. Lack of proper comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Duplicated code2 Long method3 Feature envy4 Inconsistent naming conventions (eg type, Type)5 Inconsistent spacing/tabs6 Mixing of responsibilities (eg converting types, analyzing type)7 Use of instanceof8 Complex nested conditionals9 Magic numbers/strings (eg "Array", "Map") | t | f | f | . Duplicated code2. Long method3. Feature envy4. Inconsistent naming conventions (e.g. type, Type)5. Inconsistent spacing/tabs6. Mixing of responsibilities (e.g. converting types, analyzing type)7. Use of instanceof8. Complex nested conditionals9. Magic numbers/strings (e.g. "Array", "Map") | data class | 0 | 4302 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 441 | 4302 |
| 443 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | data class | t | t | t | 0 | 4309 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 1 | 443 | 4309 | ||
| 443 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 4309 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 2 | 443 | 4309 |
| 444 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | data class | t | t | t | 0 | 4319 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 1 | 444 | 4319 | ||
| 444 | YES I found bad smells - the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 4319 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 2 | 444 | 4319 |
| 445 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void rule__Action__OperatorAssignment_2_2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtextGrammarTestLanguage.g:6076:1: ( ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) ) // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) { // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) // InternalXtextGrammarTestLanguage.g:6078:3: ( rule__Action__OperatorAlternatives_2_2_0 ) { before(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); // InternalXtextGrammarTestLanguage.g:6079:3: ( rule__Action__OperatorAlternatives_2_2_0 ) // InternalXtextGrammarTestLanguage.g:6079:4: rule__Action__OperatorAlternatives_2_2_0 { pushFollow(FOLLOW_2); rule__Action__OperatorAlternatives_2_2_0(); state._fsp--; } after(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } |
long method | the bad smells are: long method | t | t | t | 0 | 4346 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/xtextgrammar/ide/contentassist/antlr/internal/InternalXtextGrammarTestLanguageParser.java/#L18472-L18513 | 1 | 445 | 4346 | ||
| 445 | YES I found bad smells. The bad smells are: 1. Long method 2. Redundant code 3. Code duplication 4. Complex control flow 5. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void rule__Action__OperatorAssignment_2_2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtextGrammarTestLanguage.g:6076:1: ( ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) ) // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) { // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) // InternalXtextGrammarTestLanguage.g:6078:3: ( rule__Action__OperatorAlternatives_2_2_0 ) { before(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); // InternalXtextGrammarTestLanguage.g:6079:3: ( rule__Action__OperatorAlternatives_2_2_0 ) // InternalXtextGrammarTestLanguage.g:6079:4: rule__Action__OperatorAlternatives_2_2_0 { pushFollow(FOLLOW_2); rule__Action__OperatorAlternatives_2_2_0(); state._fsp--; } after(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } |
long method | Long method 2 Redundant code 3 Code duplication 4 Complex control flow 5 Inconsistent naming conventions | t | f | t | 0 | 4346 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/xtextgrammar/ide/contentassist/antlr/internal/InternalXtextGrammarTestLanguageParser.java/#L18472-L18513 | 2 | 445 | 4346 | ||
| 446 | YES I found bad smells the bad smells are: 1.Long method 2.Low cohesion 3.Magic numbers 4.Inefficient variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | Long method 2Low cohesion 3Magic numbers 4Inefficient variable naming | t | f | f | .Long method 2.Low cohesion 3.Magic numbers 4.Inefficient variable naming | data class | 0 | 4357 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 2 | 446 | 4357 |
| 447 | {"response": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | 1. data class | t | t | f | data class | 0 | 4364 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 1 | 447 | 4364 | |
| 447 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4364 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 2 | 447 | 4364 |
| 448 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | long method | t | t | t | 0 | 4366 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 1 | 448 | 4366 | ||
| 448 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4366 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 2 | 448 | 4366 | ||
| 449 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 4369 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 449 | 4369 | |
| 449 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method | t | f | t | 0 | 4369 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 449 | 4369 | ||
| 450 | {"output":"YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | 1. long method | t | t | f | long method | 0 | 4392 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 450 | 4392 | |
| 450 | YES, I found bad smells. The bad smells are: 1. Magic literal - the "unchecked" in the @SuppressWarnings annotation, makes it hard to understand the purpose of suppressing warnings. 2. Long method - the method handleBulkLoad is long and contains multiple nested loops and conditions, which makes it hard to read and understand. 3. Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain. 4. Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods. 5. Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about. 6. Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues. 7. Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug. 8. Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read. 9. Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Magic literal - the "unchecked" in the @SuppressWarnings annotation, makes it hard to understand the purpose of suppressing warnings2 Long method - the method handleBulkLoad is long and contains multiple nested loops and conditions, which makes it hard to read and understand3 Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain4 Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods5 Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about6 Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues7 Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug8 Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read9 Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain | t | f | t | . Magic literal - the "unchecked" in the @SuppressWarnings annotation, which makes it hard to read and understand.3. Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain.4. Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods.5. Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about.6. Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues.7. Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug.8. Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read.9. Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain. | 0 | 4392 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 450 | 4392 | |
| 452 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static TimeOfYear fromDateTime(DateTime dateTime) { DateTime nextYear = dateTime.plusYears(1); // This turns February 29 into February 28. TimeOfYear instance = new TimeOfYear(); instance.timeString = String.format( "%02d %02d %08d", nextYear.getMonthOfYear(), nextYear.getDayOfMonth(), nextYear.getMillisOfDay()); return instance; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 4409 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/common/TimeOfYear.java/#L61-L70 | 1 | 452 | 4409 |
| 452 | YES, I found bad smells the bad smells are: Long method, Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static TimeOfYear fromDateTime(DateTime dateTime) { DateTime nextYear = dateTime.plusYears(1); // This turns February 29 into February 28. TimeOfYear instance = new TimeOfYear(); instance.timeString = String.format( "%02d %02d %08d", nextYear.getMonthOfYear(), nextYear.getDayOfMonth(), nextYear.getMillisOfDay()); return instance; } |
feature envy | Long method, Message chains | t | f | f | Long method, Message chains | feature envy | 0 | 4409 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/common/TimeOfYear.java/#L61-L70 | 2 | 452 | 4409 |
| 454 | {"response": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ExpressionNode { String evaluateAsString(Context context); Object evaluateAsObject(Context context); long evaluateAsLong(Context context); double evaluateAsDouble(Context context); boolean evaluateAsBoolean(Context context); } |
data class | data class | t | t | t | 0 | 4439 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java/#L27-L39 | 1 | 454 | 4439 | ||
| 454 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ExpressionNode { String evaluateAsString(Context context); Object evaluateAsObject(Context context); long evaluateAsLong(Context context); double evaluateAsDouble(Context context); boolean evaluateAsBoolean(Context context); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4439 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java/#L27-L39 | 2 | 454 | 4439 |
| 457 | YES I found bad smells the bad smells are: 1.Long method, 2.Data class, 3.Feature envy, 4.Magic number, 5.Duplicate code, 6.Inappropriate constant, 7.Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method, 2Data class, 3Feature envy, 4Magic number, 5Duplicate code, 6Inappropriate constant, 7Message chains | t | f | t | .Long method, 3.Feature envy, 4.Magic number, 5.Duplicate code, 6.Inappropriate constant, 7.Message chains | 0 | 4454 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 457 | 4454 | |
| 459 | {"answer": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 4459 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 459 | 4459 |
| 459 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4459 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 459 | 4459 |
| 460 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 4462 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 1 | 460 | 4462 | ||
| 460 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 4462 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 2 | 460 | 4462 |
| 461 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BytesRef next() { if (input.position() < end) { try { int code = input.readVInt(); boolean newField = (code & 1) != 0; if (newField) { field = input.readString(); } int prefix = code >>> 1; int suffix = input.readVInt(); readTermBytes(prefix, suffix); return bytes; } catch (IOException e) { throw new RuntimeException(e); } } else { field = null; return null; } } |
long method | long method | t | t | t | 0 | 4463 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java/#L123-L143 | 1 | 461 | 4463 | ||
| 461 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BytesRef next() { if (input.position() < end) { try { int code = input.readVInt(); boolean newField = (code & 1) != 0; if (newField) { field = input.readString(); } int prefix = code >>> 1; int suffix = input.readVInt(); readTermBytes(prefix, suffix); return bytes; } catch (IOException e) { throw new RuntimeException(e); } } else { field = null; return null; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4463 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java/#L123-L143 | 2 | 461 | 4463 | ||
| 462 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | 1. long method | t | t | t | 0 | 4467 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 1 | 462 | 4467 | ||
| 462 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 4467 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 2 | 462 | 4467 | ||
| 463 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Misplaced Class 5. Data Clumps 6. Primitive Obsession 7. Inappropriate Intimacy 8. Lazy Class 9. Middle Man 10. Message Chains 11. Shotgun Surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | Long Method 2 Feature Envy 3 Duplicate Code 4 Misplaced Class 5 Data Clumps 6 Primitive Obsession 7 Inappropriate Intimacy 8 Lazy Class 9 Middle Man | t | f | f | . Long Method 2. Feature Envy 3. Duplicate Code 4. Misplaced Class 5. Data Clumps 6. Primitive Obsession 7. Inappropriate Intimacy 8. Lazy Class 9. Middle Man | data class | 0 | 4487 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 2 | 463 | 4487 |
| 465 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | data class | t | t | t | 0 | 4508 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 465 | 4508 | ||
| 466 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | long method | t | t | t | 0 | 4523 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 1 | 466 | 4523 | ||
| 466 | the bad smells are: 1. Long method 2. Feature envy 3. Conditional complexity (multiple nested if statements) 4. Inconsistent formatting and indentation 5. Unclear variable names 6. Lack of comments/documentation 7. Duplicate code (throwing the same exception for different conditions) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | Long method2 Feature envy3 Conditional complexity (multiple nested if statements)4 Inconsistent formatting and indentation 5 Unclear variable names 6 Lack of comments/documentation 7 Duplicate code (throwing the same exception for different conditions) | f | f | t | 0 | 4523 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 2 | 466 | 4523 | ||
| 467 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Element(endTag=false) public interface LINK extends Attrs, _Child { // $charset omitted /** URI for linked resource * @param uri the URI * @return the current element builder */ LINK $href(String uri); /** language code * @param cdata the code * @return the current element builder */ LINK $hreflang(String cdata); /** advisory content type * @param cdata the type * @return the current element builder */ LINK $type(String cdata); /** forward link types * @param linkTypes the types * @return the current element builder */ LINK $rel(EnumSet linkTypes); /** * forward link types. * @param linkTypes space-separated link types * @return the current element builder */ LINK $rel(String linkTypes); // $rev omitted. Instead of rev="made", use rel="author" /** for rendering on these media * @param mediaTypes the media types * @return the current element builder */ LINK $media(EnumSet mediaTypes); /** * for rendering on these media. * @param mediaTypes comma-separated list of media * @return the current element builder */ LINK $media(String mediaTypes); } |
data class | f | f | f | data class | 0 | 4538 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java/#L1772-L1820 | 1 | 467 | 4538 | ||
| 467 | YES I found bad smells. The bad smells are: 1. Inconsistent spacing and indentation 2. Use of vague variable and method names 3. Lack of comments and documentation for methods 4. Use of EnumSet for parameter types instead of more specific types 5. Mixing of variable types in method parameters 6. Use of abbreviated variable names (e.g. cdata) 7. Use of multiple return statements instead of a single return statement 8. Inconsistent use of parentheses for method calls 9. Mixing of code with comments 10. Lack of clarity in method functionality | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Element(endTag=false) public interface LINK extends Attrs, _Child { // $charset omitted /** URI for linked resource * @param uri the URI * @return the current element builder */ LINK $href(String uri); /** language code * @param cdata the code * @return the current element builder */ LINK $hreflang(String cdata); /** advisory content type * @param cdata the type * @return the current element builder */ LINK $type(String cdata); /** forward link types * @param linkTypes the types * @return the current element builder */ LINK $rel(EnumSet linkTypes); /** * forward link types. * @param linkTypes space-separated link types * @return the current element builder */ LINK $rel(String linkTypes); // $rev omitted. Instead of rev="made", use rel="author" /** for rendering on these media * @param mediaTypes the media types * @return the current element builder */ LINK $media(EnumSet mediaTypes); /** * for rendering on these media. * @param mediaTypes comma-separated list of media * @return the current element builder */ LINK $media(String mediaTypes); } |
data class | Inconsistent spacing and indentation2 Use of vague variable and method names 3 Lack of comments and documentation for methods 4 Use of EnumSet for parameter types instead of more specific types 5 Mixing of variable types in method parameters 6 Use of abbreviated variable names (eg cdata) 7 Use of multiple return statements instead of a single return statement 8 Inconsistent use of parentheses for method calls 9 Mixing of code with comments | t | f | f | . Inconsistent spacing and indentation2. Use of vague variable and method names 3. Lack of comments and documentation for methods 4. Use of EnumSet for parameter types instead of more specific types 5. Mixing of variable types in method parameters 6. Use of abbreviated variable names (e.g. cdata) 7. Use of multiple return statements instead of a single return statement 8. Inconsistent use of parentheses for method calls 9. Mixing of code with comments | data class | 0 | 4538 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java/#L1772-L1820 | 2 | 467 | 4538 |
| 468 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 4551 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 468 | 4551 | ||
| 468 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method | t | f | t | 0 | 4551 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 468 | 4551 | ||
| 469 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1.": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | 1.: long method | t | t | t | 0 | 4555 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 469 | 4555 | ||
| 469 | YES I found bad smells" YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method2 Feature envy | t | f | t | 0 | 4555 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 469 | 4555 | ||
| 471 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 4568 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 471 | 4568 | ||
| 471 | YES I found bad smells The bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Switch statement 5. Magic numbers (e.g. 0, 1, 2) 6. Unused variable (_s) 7. Duplicate code within cases 8. Failed state tracking 9. Indentation issues 10. Unclear variable names and method names 11. Multiple return statements within cases | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Repeated code3 Feature envy4 Switch statement5 Magic numbers (eg 0, | t | f | t | 0 | 4568 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 471 | 4568 | ||
| 472 | {"message": "YES I found bad smells", "bad_smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | data class | t | t | t | 0 | 4574 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 1 | 472 | 4574 | ||
| 472 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4574 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 2 | 472 | 4574 |
| 473 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | 1. data class | t | t | f | data class | 0 | 4576 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 1 | 473 | 4576 | |
| 473 | YES I found bad smells The bad smells are: 1. Inconsistent formatting and style - inconsistent use of spaces and indentation. 2. Unused fields and redundant constructors - the field "taskId" and the constructor are not used. 3. Poor naming convention - "TaskRemoval" is a confusing name for a class that implements "WorkerHistoryItem". 4. Feature envy - the "getTaskId()" method only uses the "taskId" field, which could easily be a method of the "WorkerHistoryItem" interface. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | Inconsistent formatting and style - inconsistent use of spaces and indentation2 Unused fields and redundant constructors - the field "taskId" and the constructor are not used3 Poor naming convention - "TaskRemoval" is a confusing name for a class that implements "WorkerHistoryItem"4 Feature envy - the "getTaskId()" method only uses the "taskId" field, which could easily be a method of the "WorkerHistoryItem" interface | t | f | f | . Inconsistent formatting and style - inconsistent use of spaces and indentation.2. Unused fields and redundant constructors - the field "taskId" and the constructor are not used.3. Poor naming convention - "TaskRemoval" is a confusing name for a class that implements "WorkerHistoryItem".4. Feature envy - the "getTaskId()" method only uses the "taskId" field, which could easily be a method of the "WorkerHistoryItem" interface. | data class | 0 | 4576 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 2 | 473 | 4576 |
| 474 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean supportsParameter(MethodParameter parameter) { if (!super.supportsParameter(parameter)) { return false; } Class type = parameter.getParameterType(); if (!type.isInterface()) { return false; } // Annotated parameter if (parameter.getParameterAnnotation(ProjectedPayload.class) != null) { return true; } // Annotated type if (AnnotatedElementUtils.findMergedAnnotation(type, ProjectedPayload.class) != null) { return true; } // Fallback for only user defined interfaces String packageName = ClassUtils.getPackageName(type); return !IGNORED_PACKAGES.stream().anyMatch(it -> packageName.startsWith(it)); } |
long method | 1. long method | t | t | f | long method | 0 | 4578 | https://github.com/spring-projects/spring-data-commons/blob/48c9297118e18273a0a3dfe3cf2f9a8ffd8fdca7/src/main/java/org/springframework/data/web/ProxyingHandlerMethodArgumentResolver.java/#L88-L115 | 1 | 474 | 4578 | |
| 474 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean supportsParameter(MethodParameter parameter) { if (!super.supportsParameter(parameter)) { return false; } Class type = parameter.getParameterType(); if (!type.isInterface()) { return false; } // Annotated parameter if (parameter.getParameterAnnotation(ProjectedPayload.class) != null) { return true; } // Annotated type if (AnnotatedElementUtils.findMergedAnnotation(type, ProjectedPayload.class) != null) { return true; } // Fallback for only user defined interfaces String packageName = ClassUtils.getPackageName(type); return !IGNORED_PACKAGES.stream().anyMatch(it -> packageName.startsWith(it)); } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 4578 | https://github.com/spring-projects/spring-data-commons/blob/48c9297118e18273a0a3dfe3cf2f9a8ffd8fdca7/src/main/java/org/springframework/data/web/ProxyingHandlerMethodArgumentResolver.java/#L88-L115 | 2 | 474 | 4578 |
| 475 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4581 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 2 | 475 | 4581 |
| 476 | {"output": "YES, I found bad smells. The bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | 1. data class | t | t | f | data class | 0 | 4588 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 1 | 476 | 4588 | |
| 476 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4588 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 2 | 476 | 4588 |
| 480 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 4632 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 2 | 480 | 4632 | ||
| 481 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4700 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 1 | 481 | 4700 |
| 481 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 4700 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 2 | 481 | 4700 |
| 482 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void removePipeline(Pipeline pipeline) { for (DatanodeDetails details : pipeline.getNodes()) { UUID dnId = details.getUuid(); dn2ObjectMap.computeIfPresent(dnId, (k, v) -> { v.remove(pipeline.getId()); return v; }); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4708 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/states/Node2PipelineMap.java/#L67-L76 | 1 | 482 | 4708 |
| 482 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void removePipeline(Pipeline pipeline) { for (DatanodeDetails details : pipeline.getNodes()) { UUID dnId = details.getUuid(); dn2ObjectMap.computeIfPresent(dnId, (k, v) -> { v.remove(pipeline.getId()); return v; }); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 4708 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/states/Node2PipelineMap.java/#L67-L76 | 2 | 482 | 4708 |
| 483 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | long method | t | t | t | 0 | 4713 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 1 | 483 | 4713 | ||
| 483 | YES I found bad smells the bad smells are: 1. Long method 2. Lack of abstraction/encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long method2 Lack of abstraction/encapsulation | t | f | t | 0 | 4713 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 2 | 483 | 4713 | ||
| 484 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | long method | t | t | t | 0 | 4743 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 1 | 484 | 4743 | ||
| 484 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | Long method2 Feature envy | t | f | t | 0 | 4743 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 2 | 484 | 4743 | ||
| 486 | { "message": "YES I found bad smells", "bad smells are:": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 4755 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 1 | 486 | 4755 | |
| 486 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 4755 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 2 | 486 | 4755 | ||
| 487 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4794 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 487 | 4794 |
| 487 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 4794 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 2 | 487 | 4794 |
| 489 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void appendXmlComparison1(SQLBuffer buf, String op, FilterValue lhs, FilterValue rhs) { boolean castrhs = false; Class rc = Filters.wrap(rhs.getType()); int type = 0; if (rhs.isConstant()) { type = getJDBCType(JavaTypes.getTypeCode(rc), false); castrhs = true; } appendXmlExists(buf, lhs); buf.append(" ").append(op).append(" "); buf.append("$"); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("]' PASSING "); appendXmlVar(buf, lhs); buf.append(", "); if (castrhs) appendCast(buf, rhs, type); else rhs.appendTo(buf); buf.append(" AS \""); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("\")"); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 4865 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DB2Dictionary.java/#L682-L717 | 2 | 489 | 4865 | |
| 490 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method | t | t | t | 0 | 4881 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 490 | 4881 | ||
| 490 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method | t | f | t | 0 | 4881 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 490 | 4881 | ||
| 491 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | 1. long method | t | t | f | long method | 0 | 4899 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 1 | 491 | 4899 | |
| 491 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4899 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 2 | 491 | 4899 | ||
| 492 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | 1. data class | t | t | f | data class | 0 | 4936 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 1 | 492 | 4936 | |
| 492 | YES, I found bad smells. The bad smells are: 1. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | Feature envy | t | f | f | . Feature envy. | data class | 0 | 4936 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 2 | 492 | 4936 |
| 493 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 4960 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 1 | 493 | 4960 | ||
| 493 | YES I found bad smells! the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4960 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 2 | 493 | 4960 |
| 494 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 4985 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 1 | 494 | 4985 |
| 494 | YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy (methods return values from private methods only in order pass them to other methods) 4. Lack of readability and understandability due to unclear method names and lack of comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Duplicated code2 Long method3 Feature envy (methods return values from private methods only in order pass them to other methods)4 Lack of readability and understandability due to unclear method names and lack of comments | t | f | f | . Duplicated code2. Long method3. Feature envy (methods return values from private methods only in order pass them to other methods)4. Lack of readability and understandability due to unclear method names and lack of comments. | data class | 0 | 4985 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 2 | 494 | 4985 |
| 495 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | long method | t | t | t | 0 | 5014 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 1 | 495 | 5014 | ||
| 495 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 5014 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 2 | 495 | 5014 | |
| 497 | { "error": "Invalid input. The provided code snippet is incomplete or not formatted correctly." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | f | f | f | data class | 0 | 5043 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 1 | 497 | 5043 | ||
| 497 | public class ModifierOp extends BasicOperation {ModifierOp(int type) { super(type); }CODE NOT FOUND YES I found bad smells the bad smells are: 1. Non-descriptive variable names (v1, v2) 2. Multiple parameters for constructor 3. Duplication of super constructor call in child constructor 4. Getter methods returning the values of private variables, instead of methods in the class that manipulates those variables 5. Misplaced and irrelevant comments 6. Inconsistent indentation and formatting 7. Unused and redundant code (ModifierOp constructor with no body) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | Non-descriptive variable names (v | t | f | f | . Non-descriptive variable names (v | data class | 0 | 5043 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 2 | 497 | 5043 |
| 500 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | data class | t | t | t | 0 | 5070 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 1 | 500 | 5070 | ||
| 500 | YES I found bad smells the bad smells are: 1. Long method 2. Data clumps 3. Duplicated code 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long method2 Data clumps3 Duplicated code4 Feature envy | t | f | f | . Long method2. Data clumps3. Duplicated code4. Feature envy | data class | 0 | 5070 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 2 | 500 | 5070 |
| 501 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Feature Envy", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | feature envy, data class | t | t | f | feature envy | data class | 0 | 5079 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 1 | 501 | 5079 |
| 501 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5079 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 501 | 5079 |
| 502 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | long method | t | t | t | 0 | 5087 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 502 | 5087 | ||
| 502 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Duplicated code 4. Feature envy - code should be moved to the appropriate class instead of being implemented in the deserialize method. 5. Use of hardcoded values instead of constants or variables 6. Multiple return statements - can be simplified to one return statement outside of the switch statement 7. Code repetition, specifically in the switch cases for creating the different distributions and performing validation checks. 8. Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Long method2 Switch statement3 Duplicated code4 Feature envy - code should be moved to the appropriate class instead of being implemented in the deserialize method 5 Use of hardcoded values instead of constants or variables6 Multiple return statements - can be simplified to one return statement outside of the switch statement7 Code repetition, specifically in the switch cases for creating the different distributions and performing validation checks 8 Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting | t | f | t | specifically in the switch cases for creating the different distributions and performing validation checks. 8. Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting. | 0 | 5087 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 502 | 5087 | |
| 505 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void unitKept(IInstallableUnit unit) { super.unitKept(unit); logger.debug(" Keeping unit " + unit.getId() + "/" + unit.getVersion()); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 5129 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-bundles/org.eclipse.tycho.p2.resolver.impl/src/main/java/org/eclipse/tycho/p2/target/filters/TargetPlatformFilterEvaluator.java/#L287-L291 | 1 | 505 | 5129 |
| 505 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void unitKept(IInstallableUnit unit) { super.unitKept(unit); logger.debug(" Keeping unit " + unit.getId() + "/" + unit.getVersion()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5129 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-bundles/org.eclipse.tycho.p2.resolver.impl/src/main/java/org/eclipse/tycho/p2/target/filters/TargetPlatformFilterEvaluator.java/#L287-L291 | 2 | 505 | 5129 | ||
| 506 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | 1. long method | t | t | f | long method | 0 | 5141 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 506 | 5141 | |
| 506 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 5141 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 506 | 5141 | ||
| 507 | {"message":"YES I found bad smells","bad smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | 1. long method | t | t | f | long method | 0 | 5156 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 1 | 507 | 5156 | |
| 507 | YES I found bad smells The bad smells are: 1.Long method 2.Magic strings 3.Coupled design 4.Incomplete error handling 5.Condition redundancy 6.Poorly named variable and method names 7.Inadequate commenting/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long method2Magic strings3Coupled design4Incomplete error handling5Condition redundancy6Poorly named variable and method names7Inadequate commenting/documentation | t | f | t | 0 | 5156 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 2 | 507 | 5156 | ||
| 508 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 5157 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 2 | 508 | 5157 |
| 510 | {"message": "YES I found bad smells", "bad smells are:": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | long method | t | t | f | long method | data class | 0 | 5190 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 1 | 510 | 5190 |
| 510 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5190 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 2 | 510 | 5190 |
| 513 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | long method | t | t | t | 0 | 5219 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 1 | 513 | 5219 | ||
| 513 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | Long method, 2 Duplicate code, 3 Feature envy | t | f | t | 2. Duplicate code, 3. Feature envy | 0 | 5219 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 2 | 513 | 5219 | |
| 514 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | data class | t | t | t | 0 | 5287 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 1 | 514 | 5287 | ||
| 514 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5287 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 2 | 514 | 5287 |
| 517 | { "message": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | long method | t | t | t | 0 | 5350 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 1 | 517 | 5350 | ||
| 517 | "YES I found bad smells: Long method, Feature envy, Complex conditionals, Inconsistent name, Hardcoded numbers, "the bad smells are: 1. Long method 2. Feature envy 3. Complex conditionals 4. Inconsistent name 5. Hardcoded numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | Long method2 Feature envy3 Complex conditionals4 Inconsistent name5 Hardcoded numbers | t | f | t | 0 | 5350 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 2 | 517 | 5350 | ||
| 519 | {"message": "YES, I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
data class | data class | t | t | t | 0 | 5404 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 1 | 519 | 5404 | ||
| 521 | {"error": "Sorry, unable to analyze Java code without the actual code provided."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator> iterator() { return immutableComparatorRegistry.iterator(); } |
feature envy | Not specified | f | f | f | false | 0 | 5410 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/registries/ImmutableComparatorRegistry.java/#L148-L152 | 1 | 521 | 5410 | |
| 521 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator> iterator() { return immutableComparatorRegistry.iterator(); } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 5410 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/registries/ImmutableComparatorRegistry.java/#L148-L152 | 2 | 521 | 5410 | |
| 522 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static ResumptionAction fromName(String name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } for (int i = 0; i < PRIVATE_VALUES.length; i++) { if (name.equals(PRIVATE_VALUES[i].name)) { return PRIVATE_VALUES[i]; } } throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 5419 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/ResumptionAction.java/#L79-L92 | 1 | 522 | 5419 |
| 522 | YES I found bad smells The bad smells are: 1. Long method 2. Magic number 3. Feature envy 4. Inconsistent formatting 5. Indentation issue 6. Unnecessary variable declaration 7. Use of for loop instead of enhanced for loop 8. Unnecessary exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static ResumptionAction fromName(String name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } for (int i = 0; i < PRIVATE_VALUES.length; i++) { if (name.equals(PRIVATE_VALUES[i].name)) { return PRIVATE_VALUES[i]; } } throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } |
feature envy | Long method2 Magic number3 Feature envy4 Inconsistent formatting5 Indentation issue6 Unnecessary variable declaration7 Use of for loop instead of enhanced for loop8 Unnecessary exception handling | t | f | t | 0 | 5419 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/ResumptionAction.java/#L79-L92 | 2 | 522 | 5419 | ||
| 527 | {"message": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | feature envy | t | t | t | 0 | 5449 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 1 | 527 | 5449 | ||
| 527 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5449 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 2 | 527 | 5449 | ||
| 528 | { "message": "YES I found bad smells", "detected_bad_smells": { "the_bad_smells_are": [ "Long Method", "Feature Envy" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | the_bad_smells_are: long method, feature envy | t | t | f | the_bad_smells_are: long method | feature envy | 0 | 5451 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 528 | 5451 |
| 528 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Commented out code 4. Use of magic numbers 5. Feature envy 6. Use of arrays instead of data structures 7. Poor variable and parameter naming (i.e. angles, it, i) 8. Inconsistent spacing and formatting 9. Lack of proper exception handling 10. Inefficient use of loops and iterators 11. Unnecessary complexity in calculations with geometric parameters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | Long method2 Duplicate code3 Commented out code4 Use of magic numbers5 Feature envy6 Use of arrays instead of data structures7 Poor variable and parameter naming (ie angles, it, i)8 Inconsistent spacing and formatting9 Lack of proper exception handling | t | f | t | it, i)8. Inconsistent spacing and formatting9. Lack of proper exception handling | 0 | 5451 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 528 | 5451 | |
| 530 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 5476 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 1 | 530 | 5476 |
| 530 | YES I found bad smells the bad smells are: Long method, Feature envy, Inappropriate intimacy, Inconsistent naming, Duplicate code, Lazy class, Inconsistent formatting, Commented code, Message chains. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | Long method, Feature envy, Inappropriate intimacy, Inconsistent naming, Duplicate code, Lazy class, Inconsistent formatting, Commented code, Message chains | t | f | f | Long method, Feature envy, Inappropriate intimacy, Inconsistent naming, Duplicate code, Lazy class, Inconsistent formatting, Commented code, Message chains. | data class | 0 | 5476 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 2 | 530 | 5476 |
| 533 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
data class | long method | t | t | f | long method | data class | 0 | 5479 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 1 | 533 | 5479 |
| 533 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 5479 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 2 | 533 | 5479 |
| 534 | {"message": "YES I found bad smells the bad smells are: 2. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | 2. data class | t | t | f | data class | 0 | 5480 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 534 | 5480 | |
| 534 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 5480 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 534 | 5480 |
| 535 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 5486 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 1 | 535 | 5486 | |
| 537 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 5493 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 1 | 537 | 5493 |
| 537 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5493 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 537 | 5493 | ||
| 538 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | 1. data class | t | t | f | data class | 0 | 5500 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 1 | 538 | 5500 | |
| 538 | YES I found bad smells the bad smells are: 1. Long constructor 2. Redundant ternary operation 3. Poor naming conventions for variables 4. Lack of encapsulation for instance variables 5. Unnecessary use of intern() method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | Long constructor2 Redundant ternary operation3 Poor naming conventions for variables4 Lack of encapsulation for instance variables5 Unnecessary use of intern() method | t | f | f | . Long constructor2. Redundant ternary operation3. Poor naming conventions for variables4. Lack of encapsulation for instance variables5. Unnecessary use of intern() method | data class | 0 | 5500 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 2 | 538 | 5500 |
| 539 | ] 502.Bad comments 507.Long class 510.Duplicate code 511.Unused code 514.Magic numbers 516.Method chaining 518.Lazy class 520.Long parameter list 522.Data class 525.God class 526.Lazy initialization 529.Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class MachOSymtab { /** * ByteBuffer holding the LC_SYMTAB command contents. */ private final ByteBuffer symtabCmd; private int symtabDataSize; private final ArrayList localSymbols = new ArrayList<>(); private final ArrayList globalSymbols = new ArrayList<>(); private final ArrayList undefSymbols = new ArrayList<>(); /** * Number of symbols added. */ private int symbolCount; /** * String holding symbol table strings. */ private final StringBuilder strTabContent = new StringBuilder(); /** * Keeps track of bytes in string table since strTabContent.length() is number of chars, not * bytes. */ private int strTabNrOfBytes = 0; MachOSymtab() { symtabCmd = MachOByteBuffer.allocate(symtab_command.totalsize); symtabCmd.putInt(symtab_command.cmd.off, symtab_command.LC_SYMTAB); symtabCmd.putInt(symtab_command.cmdsize.off, symtab_command.totalsize); symbolCount = 0; } static int getAlign() { return (4); } MachOSymbol addSymbolEntry(String name, byte type, byte secHdrIndex, long offset) { // Get the current symbol index and append symbol name to string table. int index; MachOSymbol sym; if (name.isEmpty()) { index = 0; strTabContent.append('\0'); strTabNrOfBytes += 1; sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); localSymbols.add(sym); } else { // We can't trust strTabContent.length() since that is // chars (UTF16), keep track of bytes on our own. index = strTabNrOfBytes; strTabContent.append("_").append(name).append('\0'); // + 1 for null, + 1 for "_" strTabNrOfBytes += (name.getBytes().length + 1 + 1); sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); switch (type) { case nlist_64.N_EXT: undefSymbols.add(sym); break; case nlist_64.N_SECT: case nlist_64.N_UNDF: // null symbol localSymbols.add(sym); break; case nlist_64.N_SECT | nlist_64.N_EXT: globalSymbols.add(sym); break; default: System.out.println("Unsupported Symbol type " + type); break; } } symbolCount++; return (sym); } void setOffset(int symoff) { symtabCmd.putInt(symtab_command.symoff.off, symoff); } // Update the symbol indexes once all symbols have been added. // This is required since we'll be reordering the symbols in the // file to be in the order of Local, global and Undefined. void updateIndexes() { int index = 0; // Update the local symbol indexes for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); sym.setIndex(index++); } // Update the global symbol indexes for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); sym.setIndex(index++); } // Update the undefined symbol indexes for (int i = index; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); sym.setIndex(index++); } } // Update LC_SYMTAB command fields based on the number of symbols added // return the file size taken up by symbol table entries and strings int calcSizes() { int stroff; stroff = symtabCmd.getInt(symtab_command.symoff.off) + (nlist_64.totalsize * symbolCount); symtabCmd.putInt(symtab_command.nsyms.off, symbolCount); symtabCmd.putInt(symtab_command.stroff.off, stroff); symtabCmd.putInt(symtab_command.strsize.off, strTabNrOfBytes); symtabDataSize = (nlist_64.totalsize * symbolCount) + strTabNrOfBytes; return (symtabDataSize); } int getNumLocalSyms() { return localSymbols.size(); } int getNumGlobalSyms() { return globalSymbols.size(); } int getNumUndefSyms() { return undefSymbols.size(); } byte[] getCmdArray() { return symtabCmd.array(); } // Create a single byte array that contains the symbol table entries // and string table byte[] getDataArray() { ByteBuffer symtabData = MachOByteBuffer.allocate(symtabDataSize); byte[] retarray; // Add the local symbols for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the global symbols for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the undefined symbols for (int i = 0; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the stringtable byte[] strs = strTabContent.toString().getBytes(); symtabData.put(strs); retarray = symtabData.array(); return (retarray); } } |
data class | 0Duplicate code5 | f | f | f | 0.Duplicate code5 | data class | 0 | 5502 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/macho/MachOSymtab.java/#L34-L209 | 2 | 539 | 5502 |
| 539 | {"result": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class MachOSymtab { /** * ByteBuffer holding the LC_SYMTAB command contents. */ private final ByteBuffer symtabCmd; private int symtabDataSize; private final ArrayList localSymbols = new ArrayList<>(); private final ArrayList globalSymbols = new ArrayList<>(); private final ArrayList undefSymbols = new ArrayList<>(); /** * Number of symbols added. */ private int symbolCount; /** * String holding symbol table strings. */ private final StringBuilder strTabContent = new StringBuilder(); /** * Keeps track of bytes in string table since strTabContent.length() is number of chars, not * bytes. */ private int strTabNrOfBytes = 0; MachOSymtab() { symtabCmd = MachOByteBuffer.allocate(symtab_command.totalsize); symtabCmd.putInt(symtab_command.cmd.off, symtab_command.LC_SYMTAB); symtabCmd.putInt(symtab_command.cmdsize.off, symtab_command.totalsize); symbolCount = 0; } static int getAlign() { return (4); } MachOSymbol addSymbolEntry(String name, byte type, byte secHdrIndex, long offset) { // Get the current symbol index and append symbol name to string table. int index; MachOSymbol sym; if (name.isEmpty()) { index = 0; strTabContent.append('\0'); strTabNrOfBytes += 1; sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); localSymbols.add(sym); } else { // We can't trust strTabContent.length() since that is // chars (UTF16), keep track of bytes on our own. index = strTabNrOfBytes; strTabContent.append("_").append(name).append('\0'); // + 1 for null, + 1 for "_" strTabNrOfBytes += (name.getBytes().length + 1 + 1); sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); switch (type) { case nlist_64.N_EXT: undefSymbols.add(sym); break; case nlist_64.N_SECT: case nlist_64.N_UNDF: // null symbol localSymbols.add(sym); break; case nlist_64.N_SECT | nlist_64.N_EXT: globalSymbols.add(sym); break; default: System.out.println("Unsupported Symbol type " + type); break; } } symbolCount++; return (sym); } void setOffset(int symoff) { symtabCmd.putInt(symtab_command.symoff.off, symoff); } // Update the symbol indexes once all symbols have been added. // This is required since we'll be reordering the symbols in the // file to be in the order of Local, global and Undefined. void updateIndexes() { int index = 0; // Update the local symbol indexes for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); sym.setIndex(index++); } // Update the global symbol indexes for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); sym.setIndex(index++); } // Update the undefined symbol indexes for (int i = index; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); sym.setIndex(index++); } } // Update LC_SYMTAB command fields based on the number of symbols added // return the file size taken up by symbol table entries and strings int calcSizes() { int stroff; stroff = symtabCmd.getInt(symtab_command.symoff.off) + (nlist_64.totalsize * symbolCount); symtabCmd.putInt(symtab_command.nsyms.off, symbolCount); symtabCmd.putInt(symtab_command.stroff.off, stroff); symtabCmd.putInt(symtab_command.strsize.off, strTabNrOfBytes); symtabDataSize = (nlist_64.totalsize * symbolCount) + strTabNrOfBytes; return (symtabDataSize); } int getNumLocalSyms() { return localSymbols.size(); } int getNumGlobalSyms() { return globalSymbols.size(); } int getNumUndefSyms() { return undefSymbols.size(); } byte[] getCmdArray() { return symtabCmd.array(); } // Create a single byte array that contains the symbol table entries // and string table byte[] getDataArray() { ByteBuffer symtabData = MachOByteBuffer.allocate(symtabDataSize); byte[] retarray; // Add the local symbols for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the global symbols for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the undefined symbols for (int i = 0; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the stringtable byte[] strs = strTabContent.toString().getBytes(); symtabData.put(strs); retarray = symtabData.array(); return (retarray); } } |
data class | data class | t | t | t | 0 | 5502 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/macho/MachOSymtab.java/#L34-L209 | 1 | 539 | 5502 | ||
| 540 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | data class | t | t | t | 0 | 5535 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 1 | 540 | 5535 | ||
| 540 | YES I found bad smells the bad smells are: 1. Long method 2. Primitive obsession (using primitive types for non-trivial data, such as Boolean and String) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Long method2 Primitive obsession (using primitive types for non-trivial data, such as Boolean and String) | t | f | f | . Long method2. Primitive obsession (using primitive types for non-trivial data, such as Boolean and String) | data class | 0 | 5535 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 2 | 540 | 5535 |
| 541 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | 1: long method | t | t | f | 1: long method | data class | 0 | 5537 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 1 | 541 | 5537 |
| 541 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers (42) 4. Useless constructor injection (the 'id' variable is not used in the constructor) 5. Useless annotations (@Accessors and @Pure) 6. Useless method naming (testFunction1, testFunction2, testFunction3) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | Long method2 Feature envy3 Magic numbers (42)4 Useless constructor injection (the 'id' variable is not used in the constructor)5 Useless annotations (@Accessors and @Pure)6 Useless method naming (testFunction | t | f | f | . Long method2. Feature envy3. Magic numbers (42)4. Useless constructor injection (the 'id' variable is not used in the constructor)5. Useless annotations (@Accessors and @Pure)6. Useless method naming (testFunction | data class | 0 | 5537 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 2 | 541 | 5537 |
| 542 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 5540 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 1 | 542 | 5540 |
| 542 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5540 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 542 | 5540 | ||
| 543 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 5544 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 543 | 5544 |
| 543 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 5544 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 543 | 5544 | |
| 544 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | 1. long method | t | t | f | long method | 0 | 5546 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 544 | 5546 | |
| 544 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5546 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 544 | 5546 | ||
| 545 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5547 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 545 | 5547 |
| 545 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Repeated code (oatMagicAndVersion) 4. Magic numbers (4, 3, 12) 5. Code duplication in the switch statement (result assignment) 6. Nested try/catch statements 7. Exception handling within a finally block 8. Multiple exit points in the method (return statement within the switch statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
feature envy | Long method2 Feature envy3 Repeated code (oatMagicAndVersion)4 Magic numbers (4, 3, | t | f | t | 3, | 0 | 5547 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 545 | 5547 | |
| 546 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements MethodInterceptor { // ~ Instance fields // ================================================================================================ private MethodSecurityMetadataSource securityMetadataSource; // ~ Methods // ======================================================================================================== public Class getSecureObjectClass() { return MethodInvocation.class; } /** * This method should be used to enforce security on a MethodInvocation. * * @param mi The method being invoked which requires a security decision * * @return The returned value from the method invocation (possibly modified by the * {@code AfterInvocationManager}). * * @throws Throwable if any error occurs */ public Object invoke(MethodInvocation mi) throws Throwable { InterceptorStatusToken token = super.beforeInvocation(mi); Object result; try { result = mi.proceed(); } finally { super.finallyInvocation(token); } return super.afterInvocation(token, result); } public MethodSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 5550 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptor.java/#L40-L88 | 1 | 546 | 5550 |
| 546 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements MethodInterceptor { // ~ Instance fields // ================================================================================================ private MethodSecurityMetadataSource securityMetadataSource; // ~ Methods // ======================================================================================================== public Class getSecureObjectClass() { return MethodInvocation.class; } /** * This method should be used to enforce security on a MethodInvocation. * * @param mi The method being invoked which requires a security decision * * @return The returned value from the method invocation (possibly modified by the * {@code AfterInvocationManager}). * * @throws Throwable if any error occurs */ public Object invoke(MethodInvocation mi) throws Throwable { InterceptorStatusToken token = super.beforeInvocation(mi); Object result; try { result = mi.proceed(); } finally { super.finallyInvocation(token); } return super.afterInvocation(token, result); } public MethodSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 5550 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptor.java/#L40-L88 | 2 | 546 | 5550 |
| 547 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface IAopReferenceModel { void start(); void shutdown(); void removeProject(IJavaProject project); void addProject(IJavaProject project, IAopProject aopProject); void fireModelChanged(); List getAdviceDefinition(IJavaElement je); List getAllReferences(); List getAllReferencesForResource(IResource resource); IAopProject getProject(IJavaProject project); Collection getProjects(); boolean isAdvice(IJavaElement je); boolean isAdvised(IJavaElement je); boolean isAdvised(IBean bean); void registerAopModelChangedListener(IAopModelChangedListener listener); void unregisterAopModelChangedListener(IAopModelChangedListener listener); void clearProjects(); } |
data class | f | f | f | data class | 0 | 5553 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.aop.core/src/org/springframework/ide/eclipse/aop/core/model/IAopReferenceModel.java/#L24-L58 | 1 | 547 | 5553 | ||
| 547 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface IAopReferenceModel { void start(); void shutdown(); void removeProject(IJavaProject project); void addProject(IJavaProject project, IAopProject aopProject); void fireModelChanged(); List getAdviceDefinition(IJavaElement je); List getAllReferences(); List getAllReferencesForResource(IResource resource); IAopProject getProject(IJavaProject project); Collection getProjects(); boolean isAdvice(IJavaElement je); boolean isAdvised(IJavaElement je); boolean isAdvised(IBean bean); void registerAopModelChangedListener(IAopModelChangedListener listener); void unregisterAopModelChangedListener(IAopModelChangedListener listener); void clearProjects(); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 5553 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.aop.core/src/org/springframework/ide/eclipse/aop/core/model/IAopReferenceModel.java/#L24-L58 | 2 | 547 | 5553 |
| 548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 5554 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 548 | 5554 |
| 548 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5554 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 548 | 5554 | ||
| 549 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | data class | t | t | t | 0 | 5558 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 1 | 549 | 5558 | ||
| 549 | YES I found bad smells the bad smells are: 1. Data class 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Data class2 Feature envy | t | f | t | 0 | 5558 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 2 | 549 | 5558 | ||
| 550 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void uncompressed(Blackhole blackhole) { final ImmutableConciseSet set = ImmutableConciseSet.complement(null, emptyRows); blackhole.consume(set); assert (emptyRows == set.size()); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 5563 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/benchmarks/src/main/java/org/apache/druid/benchmark/ConciseComplementBenchmark.java/#L43-L51 | 1 | 550 | 5563 |
| 550 | The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void uncompressed(Blackhole blackhole) { final ImmutableConciseSet set = ImmutableConciseSet.complement(null, emptyRows); blackhole.consume(set); assert (emptyRows == set.size()); } |
feature envy | Long method2 Feature envy | f | f | t | 0 | 5563 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/benchmarks/src/main/java/org/apache/druid/benchmark/ConciseComplementBenchmark.java/#L43-L51 | 2 | 550 | 5563 | ||
| 551 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5564 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 1 | 551 | 5564 |
| 551 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5564 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 2 | 551 | 5564 | ||
| 554 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 5603 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 1 | 554 | 5603 | ||
| 554 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy 2 Long method | t | f | f | . Feature envy 2. Long method. | data class | 0 | 5603 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 2 | 554 | 5603 |
| 556 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Optional removeUncomparableFieldsFromRecord(Schema record, Set processed) { Preconditions.checkArgument(record.getType() == Schema.Type.RECORD); if (processed.contains(record)) { return Optional.absent(); } processed.add(record); List fields = Lists.newArrayList(); for (Field field : record.getFields()) { Optional newFieldSchema = removeUncomparableFields(field.schema(), processed); if (newFieldSchema.isPresent()) { fields.add(new Field(field.name(), newFieldSchema.get(), field.doc(), field.defaultValue())); } } Schema newSchema = Schema.createRecord(record.getName(), record.getDoc(), record.getNamespace(), false); newSchema.setFields(fields); return Optional.of(newSchema); } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 5609 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java/#L615-L634 | 1 | 556 | 5609 |
| 556 | YES, bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Optional removeUncomparableFieldsFromRecord(Schema record, Set processed) { Preconditions.checkArgument(record.getType() == Schema.Type.RECORD); if (processed.contains(record)) { return Optional.absent(); } processed.add(record); List fields = Lists.newArrayList(); for (Field field : record.getFields()) { Optional newFieldSchema = removeUncomparableFields(field.schema(), processed); if (newFieldSchema.isPresent()) { fields.add(new Field(field.name(), newFieldSchema.get(), field.doc(), field.defaultValue())); } } Schema newSchema = Schema.createRecord(record.getName(), record.getDoc(), record.getNamespace(), false); newSchema.setFields(fields); return Optional.of(newSchema); } |
feature envy | Long Method2 Feature Envy | t | f | t | 0 | 5609 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java/#L615-L634 | 2 | 556 | 5609 | ||
| 557 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class FontDelegate { private static int[] defaultMapping = { CONTROL_TEXT_FONT, SYSTEM_TEXT_FONT, USER_TEXT_FONT, CONTROL_TEXT_FONT, CONTROL_TEXT_FONT, SUB_TEXT_FONT }; FontUIResource[] fonts; // menu and window are mapped to controlFont public FontDelegate() { fonts = new FontUIResource[6]; } public FontUIResource getFont(int type) { int mappedType = defaultMapping[type]; if (fonts[type] == null) { Font f = getPrivilegedFont(mappedType); if (f == null) { f = new Font(getDefaultFontName(type), getDefaultFontStyle(type), getDefaultFontSize(type)); } fonts[type] = new FontUIResource(f); } return fonts[type]; } /** * This is the same as invoking * Font.getFont(key), with the exception * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } ); } } |
data class | long method | t | t | f | long method | data class | 0 | 5616 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java/#L357-L399 | 1 | 557 | 5616 |
| 557 | YES, I found bad smells The following bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FontDelegate { private static int[] defaultMapping = { CONTROL_TEXT_FONT, SYSTEM_TEXT_FONT, USER_TEXT_FONT, CONTROL_TEXT_FONT, CONTROL_TEXT_FONT, SUB_TEXT_FONT }; FontUIResource[] fonts; // menu and window are mapped to controlFont public FontDelegate() { fonts = new FontUIResource[6]; } public FontUIResource getFont(int type) { int mappedType = defaultMapping[type]; if (fonts[type] == null) { Font f = getPrivilegedFont(mappedType); if (f == null) { f = new Font(getDefaultFontName(type), getDefaultFontStyle(type), getDefaultFontSize(type)); } fonts[type] = new FontUIResource(f); } return fonts[type]; } /** * This is the same as invoking * Font.getFont(key), with the exception * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5616 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java/#L357-L399 | 2 | 557 | 5616 |
| 558 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | long method, data class | t | t | f | long method | data class | 0 | 5621 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 1 | 558 | 5621 |
| 558 | SequenceFileReader YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Large class 5. Data class 6. Inconsistent levels of abstraction 7. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | Long method2 Feature envy3 Duplicate code4 Large class5 Data class6 Inconsistent levels of abstraction7 Inappropriate intimacy | t | f | t | 0 | 5621 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 2 | 558 | 5621 | ||
| 560 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | 1. data class | t | t | f | data class | 0 | 5653 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 1 | 560 | 5653 | |
| 560 | YES I found bad smells the bad smells are: 1. Long method (the entire code is contained in one large method) 2. Feature envy (the boolean observed is not used within this class and seems to belong to another class) 3. Poor naming (errorMsg and setErrorString could be more specific) 4. Duplicate code (the return statement is repeated in two methods) 5. Too much functionality in one class (display() method should not be combined with methods related to error handling) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | Long method (the entire code is contained in one large method)2 Feature envy (the boolean observed is not used within this class and seems to belong to another class)3 Poor naming (errorMsg and setErrorString could be more specific)4 Duplicate code (the return statement is repeated in two methods)5 Too much functionality in one class (display() method should not be combined with methods related to error handling) | t | f | f | . Long method (the entire code is contained in one large method)2. Feature envy (the boolean observed is not used within this class and seems to belong to another class)3. Poor naming (errorMsg and setErrorString could be more specific)4. Duplicate code (the return statement is repeated in two methods)5. Too much functionality in one class (display() method should not be combined with methods related to error handling) | data class | 0 | 5653 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 2 | 560 | 5653 |
| 561 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 5662 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 561 | 5662 | |
| 561 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method | t | f | t | 0 | 5662 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 561 | 5662 | ||
| 562 | { "response": "YES I found bad smells", "detected_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean mkdirs( ) { return file.mkdirs( ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5666 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/fs/LocalFile.java/#L80-L84 | 1 | 562 | 5666 |
| 562 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean mkdirs( ) { return file.mkdirs( ); } |
feature envy | Feature envy | t | f | t | 0 | 5666 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/fs/LocalFile.java/#L80-L84 | 2 | 562 | 5666 | ||
| 563 | {"response": "YES, I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OdaDimensionState extends ReportElementState { /** * The dimension being created. */ protected Dimension element = null; /** * Constructs dimension state with the design parser handler, the container * element and the container property name of the report element. * * @param handler * the design file parser handler * @param theContainer * the element that contains this one * @param prop * the slot in which this element appears */ public OdaDimensionState( ModuleParserHandler handler, DesignElement theContainer, String prop ) { super( handler, theContainer, prop ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.parser.ReportElementState#getElement() */ public DesignElement getElement( ) { return element; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(org.xml.sax.Attributes) */ public void parseAttrs( Attributes attrs ) throws XMLParserException { element = new OdaDimension( ); initElement( attrs, true ); } } |
data class | data class | t | t | t | 0 | 5681 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/parser/OdaDimensionState.java/#L25-L74 | 1 | 563 | 5681 | ||
| 563 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OdaDimensionState extends ReportElementState { /** * The dimension being created. */ protected Dimension element = null; /** * Constructs dimension state with the design parser handler, the container * element and the container property name of the report element. * * @param handler * the design file parser handler * @param theContainer * the element that contains this one * @param prop * the slot in which this element appears */ public OdaDimensionState( ModuleParserHandler handler, DesignElement theContainer, String prop ) { super( handler, theContainer, prop ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.parser.ReportElementState#getElement() */ public DesignElement getElement( ) { return element; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(org.xml.sax.Attributes) */ public void parseAttrs( Attributes attrs ) throws XMLParserException { element = new OdaDimension( ); initElement( attrs, true ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5681 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/parser/OdaDimensionState.java/#L25-L74 | 2 | 563 | 5681 |
| 564 | { "message": "YES I found bad smells", "detected_bad_smells": { "are": [ "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | are: data class | t | t | t | 0 | 5711 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 1 | 564 | 5711 | ||
| 564 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5711 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 2 | 564 | 5711 |
| 565 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
data class | data class, long method | t | t | t | long method | 0 | 5717 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 1 | 565 | 5717 | |
| 565 | YES I found bad smells the bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method. 2. Feature envy. | data class | 0 | 5717 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 2 | 565 | 5717 |
| 566 | YES I found bad smells. The bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class ProxiedNiFiClient implements NiFiClient { private final String proxiedEntity; private final NiFiClient wrappedClient; public ProxiedNiFiClient(final NiFiClient wrappedClient, final String proxiedEntity) { this.proxiedEntity = proxiedEntity; this.wrappedClient = wrappedClient; } @Override public ControllerClient getControllerClient() { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForToken(String token) { return wrappedClient.getControllerClientForToken(token); } @Override public FlowClient getFlowClient() { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForToken(String token) { return wrappedClient.getFlowClientForToken(token); } @Override public ProcessGroupClient getProcessGroupClient() { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForToken(String token) { return wrappedClient.getProcessGroupClientForToken(token); } @Override public VersionsClient getVersionsClient() { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForToken(String token) { return wrappedClient.getVersionsClientForToken(token); } @Override public void close() throws IOException { wrappedClient.close(); } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy. | data class | 0 | 5719 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiClientFactory.java/#L113-L187 | 2 | 566 | 5719 |
| 568 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 5726 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 568 | 5726 | |
| 568 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 5726 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 568 | 5726 | ||
| 569 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "Long Method" }, { "2. Feature Envy": "Feature Envy" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
long method | 1. long method: long method, 2. feature envy: feature envy | t | t | t | 2. feature envy: feature envy | 0 | 5727 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 569 | 5727 | |
| 569 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5727 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 569 | 5727 | ||
| 571 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DirContextType { private String name; private DirContextType(String name) { this.name = name; } public String toString() { return name; } /** * The type of {@link DirContext} returned by {@link ContextSource#getReadOnlyContext()} */ public static final DirContextType READ_ONLY = new DirContextType("READ_ONLY"); /** * The type of {@link DirContext} returned by {@link ContextSource#getReadWriteContext()} */ public static final DirContextType READ_WRITE = new DirContextType("READ_WRITE"); } |
data class | data class | t | t | t | 0 | 5739 | https://github.com/spring-projects/spring-ldap/blob/6a9bde34811b87b5425c05068a31ff61d7e59170/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java/#L30-L50 | 1 | 571 | 5739 | ||
| 571 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DirContextType { private String name; private DirContextType(String name) { this.name = name; } public String toString() { return name; } /** * The type of {@link DirContext} returned by {@link ContextSource#getReadOnlyContext()} */ public static final DirContextType READ_ONLY = new DirContextType("READ_ONLY"); /** * The type of {@link DirContext} returned by {@link ContextSource#getReadWriteContext()} */ public static final DirContextType READ_WRITE = new DirContextType("READ_WRITE"); } |
data class | Long method | t | f | f | .Long method | data class | 0 | 5739 | https://github.com/spring-projects/spring-ldap/blob/6a9bde34811b87b5425c05068a31ff61d7e59170/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java/#L30-L50 | 2 | 571 | 5739 |
| 573 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 5757 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 573 | 5757 |
| 573 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (methods have repeated logic instead of using variables from the class) 3. Data and code duplication (methods are repeated for toString, equals, hashCode) 4. Class is not using encapsulation (variables are marked as final, but getters and setters are not used) 5. Unnecessary constructor (not used for anything) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long method2 Feature envy (methods have repeated logic instead of using variables from the class)3 Data and code duplication (methods are repeated for toString, equals, hashCode)4 Class is not using encapsulation (variables are marked as final, but getters and setters are not used)5 Unnecessary constructor (not used for anything) | t | f | f | . Long method2. Feature envy (methods have repeated logic instead of using variables from the class)3. Data and code duplication (methods are repeated for toString, equals, hashCode)4. Class is not using encapsulation (variables are marked as final, but getters and setters are not used)5. Unnecessary constructor (not used for anything) | data class | 0 | 5757 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 573 | 5757 |
| 575 | { "output": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | data class, long method | t | t | t | data class | 0 | 5777 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 575 | 5777 | |
| 575 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplication of code 5. Inconsistent formatting and naming conventions 6. Violation of the single responsibility principle 7. Use of complex structures and data types in parameters 8. Inefficient use of variables and data structures 9. Inadequate error handling and input validation 10. Use of hard-coded or external resources without proper abstraction. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Feature envy3 Magic numbers4 Duplication of code5 Inconsistent formatting and naming conventions6 Violation of the single responsibility principle7 Use of complex structures and data types in parameters8 Inefficient use of variables and data structures9 Inadequate error handling and input validation | t | f | t | 0 | 5777 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 575 | 5777 | ||
| 576 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 5781 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 1 | 576 | 5781 | |
| 576 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5781 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 2 | 576 | 5781 |
| 577 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5782 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 577 | 5782 | ||
| 579 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method, data class | t | t | t | data class | 0 | 5784 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 579 | 5784 | |
| 579 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Long method, 2Magic numbers, 3 Feature envy | t | f | t | 2.Magic numbers, 3. Feature envy | 0 | 5784 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 579 | 5784 | |
| 580 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 5785 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 580 | 5785 |
| 580 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers/numbers used without explanation (such as "1" or "0") 3. Use of abbreviations instead of descriptive variable names (such as "tikaInputStream" instead of "tikaInputStreamReader") 4. Mixing of different responsibilities (parsing, handling metadata, creating and returning a result map) 5. Lack of proper error handling or exception handling (only a generic "throws" statement and a basic "try-catch" block in one section) 6. Excessive comments and lack of meaningful comments describing what the code does 7. Possible feature envy due to the use of "metadata.names()" and "metadata.getValues(key)" multiple times in the same method 8. Inefficient string concatenation ("dataBuilder.append(val)") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | Long method2 Magic numbers/numbers used without explanation (such as " | t | f | f | . Long method2. Magic numbers/numbers used without explanation (such as " | feature envy | 0 | 5785 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 580 | 5785 |
| 581 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | long method, data class | t | t | t | data class | 0 | 5786 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 581 | 5786 | |
| 581 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | Long method | t | f | t | 0 | 5786 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 581 | 5786 | ||
| 582 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5787 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 582 | 5787 |
| 582 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 5787 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 582 | 5787 | ||
| 583 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | data class, long method | t | t | t | long method | 0 | 5796 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 1 | 583 | 5796 | |
| 583 | YES, I found bad smells. The bad smells are: 1. Feature envy 2. Long method 3. Data clumps 4. Duplicated code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | Feature envy2 Long method3 Data clumps4 Duplicated code | t | f | f | . Feature envy2. Long method3. Data clumps4. Duplicated code | data class | 0 | 5796 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 2 | 583 | 5796 |
| 585 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); } |
data class | long method, data class | t | t | t | long method | 0 | 5805 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 | 1 | 585 | 5805 | |
| 585 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5805 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 | 2 | 585 | 5805 |
| 587 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Context getContinuationContext(Name n) throws NamingException { Object obj = lookup(n.get(0)); CannotProceedException cpe = new CannotProceedException(); cpe.setResolvedObj(obj); cpe.setEnvironment(myEnv); return NamingManager.getContinuationContext(cpe); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 5854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java/#L195-L201 | 1 | 587 | 5854 |
| 587 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Context getContinuationContext(Name n) throws NamingException { Object obj = lookup(n.get(0)); CannotProceedException cpe = new CannotProceedException(); cpe.setResolvedObj(obj); cpe.setEnvironment(myEnv); return NamingManager.getContinuationContext(cpe); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 5854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java/#L195-L201 | 2 | 587 | 5854 | |
| 589 | { "message": "YES I found bad smells", "detected_bad_smells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | long method | t | t | t | 0 | 5882 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 589 | 5882 | ||
| 589 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5882 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 589 | 5882 | ||
| 590 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | long method, data class | t | t | t | data class | 0 | 5890 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 1 | 590 | 5890 | |
| 590 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Non-descriptive variable names 6. Deprecated code 7. Code commented out and not removed 8. Code that needs to be fixed (marked by FIXME) 9. Mixing of concerns (semantic check and inheritance check) 10. Mixing of levels of abstraction (parsing per clause and adding attribute to ajAttributes) 11. Unused variables (aspectAttribute) 12. Lack of error handling (returning false without specific error message) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Non-descriptive variable names6 Deprecated code7 Code commented out and not removed8 Code that needs to be fixed (marked by FIXME)9 Mixing of concerns (semantic check and inheritance check) | t | f | t | 0 | 5890 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 2 | 590 | 5890 | ||
| 591 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { MessageDispatchNotification info = (MessageDispatchNotification)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConsumerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalLong1(wireFormat, info.getDeliverySequenceId(), bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getMessageId(), bs); return rc + 0; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 5901 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationMarshaller.java/#L77-L88 | 1 | 591 | 5901 |
| 591 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { MessageDispatchNotification info = (MessageDispatchNotification)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConsumerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalLong1(wireFormat, info.getDeliverySequenceId(), bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getMessageId(), bs); return rc + 0; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5901 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationMarshaller.java/#L77-L88 | 2 | 591 | 5901 | ||
| 592 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5902 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 592 | 5902 | ||
| 595 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Exceptions { private Exceptions() { } public static IllegalArgumentException propertyKeyCanNotBeEmpty() { return new IllegalArgumentException("Property key can not be the empty string"); } public static IllegalArgumentException propertyKeyCanNotBeNull() { return new IllegalArgumentException("Property key can not be null"); } public static IllegalArgumentException propertyValueCanNotBeNull() { return new IllegalArgumentException("Property value can not be null"); } public static IllegalArgumentException propertyKeyCanNotBeAHiddenKey(final String key) { return new IllegalArgumentException("Property key can not be a hidden key: " + key); } public static IllegalStateException propertyDoesNotExist() { return new IllegalStateException("The property does not exist as it has no key, value, or associated element"); } public static IllegalStateException propertyDoesNotExist(final Element element, final String key) { return new IllegalStateException("The property does not exist as the key has no associated value for the provided element: " + element + ":" + key); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val) { return dataTypeOfPropertyValueNotSupported(val, null); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val, final Exception rootCause) { return new IllegalArgumentException(String.format("Property value [%s] is of type %s is not supported", val, val.getClass()), rootCause); } public static IllegalStateException propertyRemovalNotSupported() { return new IllegalStateException("Property removal is not supported"); } } |
data class | long method | t | t | f | long method | data class | 0 | 5930 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Property.java/#L129-L169 | 1 | 595 | 5930 |
| 595 | YES I found bad smells. The bad smells are: 1. Long method (Contains multiple methods with similar functionality) 2. Feature envy (Methods primarily accessing and/or modifying properties of a different class instead of their own) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Exceptions { private Exceptions() { } public static IllegalArgumentException propertyKeyCanNotBeEmpty() { return new IllegalArgumentException("Property key can not be the empty string"); } public static IllegalArgumentException propertyKeyCanNotBeNull() { return new IllegalArgumentException("Property key can not be null"); } public static IllegalArgumentException propertyValueCanNotBeNull() { return new IllegalArgumentException("Property value can not be null"); } public static IllegalArgumentException propertyKeyCanNotBeAHiddenKey(final String key) { return new IllegalArgumentException("Property key can not be a hidden key: " + key); } public static IllegalStateException propertyDoesNotExist() { return new IllegalStateException("The property does not exist as it has no key, value, or associated element"); } public static IllegalStateException propertyDoesNotExist(final Element element, final String key) { return new IllegalStateException("The property does not exist as the key has no associated value for the provided element: " + element + ":" + key); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val) { return dataTypeOfPropertyValueNotSupported(val, null); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val, final Exception rootCause) { return new IllegalArgumentException(String.format("Property value [%s] is of type %s is not supported", val, val.getClass()), rootCause); } public static IllegalStateException propertyRemovalNotSupported() { return new IllegalStateException("Property removal is not supported"); } } |
data class | Long method (Contains multiple methods with similar functionality)2 Feature envy (Methods primarily accessing and/or modifying properties of a different class instead of their own) | t | f | f | . Long method (Contains multiple methods with similar functionality)2. Feature envy (Methods primarily accessing and/or modifying properties of a different class instead of their own) | data class | 0 | 5930 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Property.java/#L129-L169 | 2 | 595 | 5930 |
| 596 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | data class, long method | t | t | t | long method | 0 | 5950 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 1 | 596 | 5950 | |
| 596 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5950 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 2 | 596 | 5950 |
| 597 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | data class | t | t | t | 0 | 5956 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 1 | 597 | 5956 | ||
| 597 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5956 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 2 | 597 | 5956 |
| 598 | {"response": "YES I found bad smells. The bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | 1. long method | t | t | t | 0 | 5982 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 598 | 5982 | ||
| 598 | YES I found bad smells the bad smells are: 1. Long Method 2. Long Parameter List | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long Method2 Long Parameter List | t | f | t | 0 | 5982 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 598 | 5982 | ||
| 599 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 5988 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 1 | 599 | 5988 | ||
| 599 | YES I found bad smells the bad smells are: 1. Empty class 2. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Empty class2 Primitive obsession | t | f | f | . Empty class2. Primitive obsession | data class | 0 | 5988 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 2 | 599 | 5988 |
| 600 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | data class | t | t | t | 0 | 5993 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 1 | 600 | 5993 | ||
| 600 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5993 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 600 | 5993 |
| 602 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | data class | t | t | t | 0 | 6009 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 1 | 602 | 6009 | ||
| 602 | YES I found bad smells The bad smells are: 1. Code duplication 2. Magic numbers 3. Use of raw types in collections 4. Use of setter methods instead of constructor injection 5. Lack of encapsulation for fields 6. Violations of single responsibility principle (validation and manipulation in same method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | Code duplication2 Magic numbers3 Use of raw types in collections4 Use of setter methods instead of constructor injection5 Lack of encapsulation for fields6 Violations of single responsibility principle (validation and manipulation in same method) | t | f | f | . Code duplication2. Magic numbers3. Use of raw types in collections4. Use of setter methods instead of constructor injection5. Lack of encapsulation for fields6. Violations of single responsibility principle (validation and manipulation in same method) | data class | 0 | 6009 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 2 | 602 | 6009 |
| 603 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | data class | t | t | t | 0 | 6013 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 1 | 603 | 6013 | ||
| 603 | YES I found bad smells the bad smells are: 1. Long method 2. Code repetition 3. Inconsistent formatting and indentation 4. Lack of comments and documentation 5. Poor variable naming (e.g. "d", "v", "R") 6. Feature envy (class is performing actions that should be done by other classes) 7. Class is responsible for too many tasks (violating Single Responsibility Principle) 8. Lack of error handling and handling of invalid input 9. Use of generic and ambiguous names for methods (e.g. "getKind()") 10. Overuse of annotations (e.g. @DefinedBy(Api.COMPILER_TREE)) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | Long method2 Code repetition3 Inconsistent formatting and indentation4 Lack of comments and documentation5 Poor variable naming (eg "d", "v", "R")6 Feature envy (class is performing actions that should be done by other classes)7 Class is responsible for too many tasks (violating Single Responsibility Principle)8 Lack of error handling and handling of invalid input9 Use of generic and ambiguous names for methods (eg "getKind()") | t | f | f | . Long method2. Code repetition3. Inconsistent formatting and indentation4. Lack of comments and documentation5. Poor variable naming (e.g. "d", "v", "R")6. Feature envy (class is performing actions that should be done by other classes)7. Class is responsible for too many tasks (violating Single Responsibility Principle)8. Lack of error handling and handling of invalid input9. Use of generic and ambiguous names for methods (e.g. "getKind()") | data class | 0 | 6013 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 2 | 603 | 6013 |
| 604 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | data class | t | t | t | 0 | 6027 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 604 | 6027 | ||
| 604 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6027 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 604 | 6027 |
| 605 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method | t | t | t | 0 | 6050 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 605 | 6050 | ||
| 605 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Poor naming conventions for variables and methods 6. Nested conditional statements 7. Lack of comments or documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Poor naming conventions for variables and methods6 Nested conditional statements7 Lack of comments or documentation | t | f | t | 0 | 6050 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 605 | 6050 | ||
| 606 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | 1: long method | t | t | t | 0 | 6083 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 1 | 606 | 6083 | ||
| 606 | YES I found bad smells The bad smells are: 1. Long method 2. Magic number (128 * 1024) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | Long method2 Magic number ( | t | f | t | 0 | 6083 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 2 | 606 | 6083 | ||
| 607 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6104 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 607 | 6104 |
| 607 | YES I found bad smells: 1. Long method 2. Feature envy 3. Duplicate code 4. Violation of Single Responsibility principle 5. Lack of encapsulation 6. Use of raw types 7. Use of primitive types instead of objects 8. Lack of comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Long method 2 Feature envy 3 Duplicate code 4 Violation of Single Responsibility principle 5 Lack of encapsulation 6 Use of raw types 7 Use of primitive types instead of objects 8 Lack of comments/documentation | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Violation of Single Responsibility principle 5. Lack of encapsulation 6. Use of raw types 7. Use of primitive types instead of objects 8. Lack of comments/documentation. | data class | 0 | 6104 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 607 | 6104 |
| 608 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | data class, long method | t | t | t | long method | 0 | 6114 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 1 | 608 | 6114 | |
| 608 | YES I found bad smells the bad smells are: 1. Lack of indentation 2. Code duplication within the constructors 3. Inconsistent naming conventions (e.g. "reference" vs "newValue") 4. Lack of comments/documentation 5. Lack of error handling for the "set" method 6. Lack of validation for the "set" method parameters 7. Tight coupling between the ReferenceProperty and EntityReference classes 8. Inappropriate use of the interface, as there is only one implementation of it | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | Lack of indentation2 Code duplication within the constructors3 Inconsistent naming conventions (eg "reference" vs "newValue")4 Lack of comments/documentation5 Lack of error handling for the "set" method6 Lack of validation for the "set" method parameters 7 Tight coupling between the ReferenceProperty and EntityReference classes 8 Inappropriate use of the interface, as there is only one implementation of it | t | f | f | . Lack of indentation2. Code duplication within the constructors3. Inconsistent naming conventions (e.g. "reference" vs "newValue")4. Lack of comments/documentation5. Lack of error handling for the "set" method6. Lack of validation for the "set" method parameters 7. Tight coupling between the ReferenceProperty and EntityReference classes 8. Inappropriate use of the interface, as there is only one implementation of it | data class | 0 | 6114 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 2 | 608 | 6114 |
| 609 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | long method | t | t | t | 0 | 6124 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 609 | 6124 | ||
| 609 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6124 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 609 | 6124 | ||
| 611 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 6133 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 2 | 611 | 6133 |
| 612 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void serialize(AGeometry instance, DataOutput out) throws HyracksDataException { try { OGCGeometry geometry = instance.getGeometry(); byte[] buffer = geometry.asBinary().array(); // For efficiency, we store the size of the geometry in bytes in the first 32 bits // This allows AsterixDB to skip over this attribute if needed. out.writeInt(buffer.length); out.write(buffer); } catch (IOException e) { throw HyracksDataException.create(e); } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 6154 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-om/src/main/java/org/apache/asterix/dataflow/data/nontagged/serde/AGeometrySerializerDeserializer.java/#L63-L75 | 2 | 612 | 6154 | |
| 620 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | long method, data class | t | t | t | data class | 0 | 6215 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 1 | 620 | 6215 | |
| 620 | YES I found bad smells. the bad smells are: long method, feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | long method, feature envy | t | f | t | feature envy. | 0 | 6215 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 2 | 620 | 6215 | |
| 621 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | 1. data class | t | t | t | 0 | 6238 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 1 | 621 | 6238 | ||
| 621 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 6238 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 2 | 621 | 6238 |
| 623 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6248 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 623 | 6248 |
| 623 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6248 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 623 | 6248 | ||
| 624 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static org.apache.phoenix.coprocessor.generated.MetaDataProtos.CreateFunctionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6250 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L8189-L8194 | 1 | 624 | 6250 |
| 624 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static org.apache.phoenix.coprocessor.generated.MetaDataProtos.CreateFunctionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6250 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L8189-L8194 | 2 | 624 | 6250 | ||
| 625 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } } |
data class | long method | t | t | f | long method | data class | 0 | 6254 | https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 | 1 | 625 | 6254 |
| 625 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 6254 | https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 | 2 | 625 | 6254 |
| 627 | { "response": "YES I found bad smells", "detected_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 6267 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 1 | 627 | 6267 | |
| 627 | YES I found bad smells. the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 6267 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 2 | 627 | 6267 |
| 628 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | data class | t | t | t | 0 | 6271 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 1 | 628 | 6271 | ||
| 628 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6271 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 2 | 628 | 6271 |
| 629 | { "response": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | data class, long method | t | t | t | long method | 0 | 6279 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 1 | 629 | 6279 | |
| 629 | " YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 6279 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 629 | 6279 |
| 630 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | data class, long method | t | t | t | long method | 0 | 6286 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 630 | 6286 | |
| 630 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 6286 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 630 | 6286 |
| 631 | { "output": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6291 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 1 | 631 | 6291 | |
| 631 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 6291 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 2 | 631 | 6291 | ||
| 632 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | long method | t | t | t | 0 | 6293 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 632 | 6293 | ||
| 632 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6293 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 632 | 6293 | ||
| 633 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6294 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 633 | 6294 |
| 633 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 6294 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 633 | 6294 | ||
| 634 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean isValid(Document xml) throws SAXException{ try{ String language = "http://www.w3.org/2001/XMLSchema"; SchemaFactory factory = SchemaFactory.newInstance(language); Source source = new DOMSource(map.getSchema()); Schema schema = factory.newSchema(source); Validator validator = schema.newValidator(); validator.validate(new DOMSource(xml)); //if no exceptions where raised, the document is valid return true; } catch(IOException e) { LOG.log(POILogger.ERROR, "document is not valid", e); } return false; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6296 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java/#L243-L260 | 1 | 634 | 6296 |
| 634 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean isValid(Document xml) throws SAXException{ try{ String language = "http://www.w3.org/2001/XMLSchema"; SchemaFactory factory = SchemaFactory.newInstance(language); Source source = new DOMSource(map.getSchema()); Schema schema = factory.newSchema(source); Validator validator = schema.newValidator(); validator.validate(new DOMSource(xml)); //if no exceptions where raised, the document is valid return true; } catch(IOException e) { LOG.log(POILogger.ERROR, "document is not valid", e); } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6296 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java/#L243-L260 | 2 | 634 | 6296 | ||
| 635 | { "message": "YES I found bad smells", "detected_bad_smells": "The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | the bad smells are: 1. long method | t | t | t | 0 | 6305 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 635 | 6305 | ||
| 635 | YES I found bad smells the bad smells are: Long method, Feature envy, long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method, Feature envy, long parameter list | t | f | t | Feature envy, long parameter list | 0 | 6305 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 635 | 6305 | |
| 637 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getDeviceDisplayName() { String displayName = ""; if (this.properties == null) { return displayName; } String deviceDisplayNameOption = (String) this.properties.get(DEVICE_DISPLAY_NAME); // Use the device name from SystemService. This should be kura.device.name from // the properties file. if ("device-name".equals(deviceDisplayNameOption)) { displayName = this.systemService.getDeviceName(); } // Try to get the device hostname else if ("hostname".equals(deviceDisplayNameOption)) { displayName = this.systemService.getHostname(); } // Return the custom field defined by the user else if ("custom".equals(deviceDisplayNameOption) && this.properties.get(DEVICE_CUSTOM_NAME) instanceof String) { displayName = (String) this.properties.get(DEVICE_CUSTOM_NAME); } // Return empty string to the server else if ("server".equals(deviceDisplayNameOption)) { displayName = ""; } return displayName; } |
long method | long method | t | t | t | 0 | 6316 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceOptions.java/#L64-L91 | 1 | 637 | 6316 | ||
| 637 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getDeviceDisplayName() { String displayName = ""; if (this.properties == null) { return displayName; } String deviceDisplayNameOption = (String) this.properties.get(DEVICE_DISPLAY_NAME); // Use the device name from SystemService. This should be kura.device.name from // the properties file. if ("device-name".equals(deviceDisplayNameOption)) { displayName = this.systemService.getDeviceName(); } // Try to get the device hostname else if ("hostname".equals(deviceDisplayNameOption)) { displayName = this.systemService.getHostname(); } // Return the custom field defined by the user else if ("custom".equals(deviceDisplayNameOption) && this.properties.get(DEVICE_CUSTOM_NAME) instanceof String) { displayName = (String) this.properties.get(DEVICE_CUSTOM_NAME); } // Return empty string to the server else if ("server".equals(deviceDisplayNameOption)) { displayName = ""; } return displayName; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6316 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceOptions.java/#L64-L91 | 2 | 637 | 6316 | ||
| 639 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | data class | t | t | t | 0 | 6330 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 639 | 6330 | ||
| 639 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6330 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 639 | 6330 |
| 640 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6350 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 1 | 640 | 6350 |
| 640 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 6350 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 2 | 640 | 6350 | |
| 641 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | data class | t | t | t | 0 | 6352 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 1 | 641 | 6352 | ||
| 641 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 6352 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 2 | 641 | 6352 |
| 642 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | long method | t | t | t | 0 | 6353 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 642 | 6353 | ||
| 642 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 6353 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 642 | 6353 | ||
| 643 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method | t | t | t | 0 | 6354 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 643 | 6354 | ||
| 643 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (multiple if-else statements) 4. Inappropriate type (using String instead of a constant or boolean) 5. Inconsistent formatting (missing spaces before and after braces) 6. Poor naming of variables (sel, sql, buf) 7. Tight coupling (method is heavily reliant on external methods and objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Long method2 Feature envy3 Duplicate code (multiple if-else statements)4 Inappropriate type (using String instead of a constant or boolean)5 Inconsistent formatting (missing spaces before and after braces)6 Poor naming of variables (sel, sql, buf)7 Tight coupling (method is heavily reliant on external methods and objects) | t | f | t | sql, buf)7. Tight coupling (method is heavily reliant on external methods and objects) | 0 | 6354 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 643 | 6354 | |
| 644 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6355 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 644 | 6355 |
| 644 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6355 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 644 | 6355 | ||
| 645 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JodaDateValidator { public enum PostgresDateTimeConstant { // patterns for replacing POSTGRES_FULL_NAME_OF_DAY(true, "day"), POSTGRES_DAY_OF_YEAR(false, "ddd"), POSTGRES_DAY_OF_MONTH(false, "dd"), POSTGRES_DAY_OF_WEEK(false, "d"), POSTGRES_NAME_OF_MONTH(true, "month"), POSTGRES_ABR_NAME_OF_MONTH(true, "mon"), POSTGRES_YEAR(false, "y"), POSTGRES_ISO_4YEAR(false, "iyyy"), POSTGRES_ISO_3YEAR(false, "iyy"), POSTGRES_ISO_2YEAR(false, "iy"), POSTGRES_ISO_1YEAR(false, "i"), POSTGRES_FULL_ERA_NAME(false, "ee"), POSTGRES_NAME_OF_DAY(true, "dy"), POSTGRES_HOUR_12_NAME(false, "hh"), POSTGRES_HOUR_12_OTHER_NAME(false, "hh12"), POSTGRES_HOUR_24_NAME(false, "hh24"), POSTGRES_MINUTE_OF_HOUR_NAME(false, "mi"), POSTGRES_SECOND_OF_MINUTE_NAME(false, "ss"), POSTGRES_MILLISECOND_OF_MINUTE_NAME(false, "ms"), POSTGRES_WEEK_OF_YEAR(false, "ww"), POSTGRES_ISO_WEEK_OF_YEAR(false, "iw"), POSTGRES_MONTH(false, "mm"), POSTGRES_HALFDAY_AM(false, "am"), POSTGRES_HALFDAY_PM(false, "pm"), // pattern modifiers for deleting PREFIX_FM(false, "fm"), PREFIX_FX(false, "fx"), PREFIX_TM(false, "tm"); private final boolean hasCamelCasing; private final String name; PostgresDateTimeConstant(boolean hasCamelCasing, String name) { this.hasCamelCasing = hasCamelCasing; this.name = name; } public boolean hasCamelCasing() { return hasCamelCasing; } public String getName() { return name; } } private static final Map postgresToJodaMap = Maps.newTreeMap(new LengthDescComparator()); public static final String POSTGRES_ESCAPE_CHARACTER = "\""; // jodaTime patterns public static final String JODA_FULL_NAME_OF_DAY = "EEEE"; public static final String JODA_DAY_OF_YEAR = "D"; public static final String JODA_DAY_OF_MONTH = "d"; public static final String JODA_DAY_OF_WEEK = "e"; public static final String JODA_NAME_OF_MONTH = "MMMM"; public static final String JODA_ABR_NAME_OF_MONTH = "MMM"; public static final String JODA_YEAR = "y"; public static final String JODA_ISO_4YEAR = "xxxx"; public static final String JODA_ISO_3YEAR = "xxx"; public static final String JODA_ISO_2YEAR = "xx"; public static final String JODA_ISO_1YEAR = "x"; public static final String JODA_FULL_ERA_NAME = "G"; public static final String JODA_NAME_OF_DAY = "E"; public static final String JODA_HOUR_12_NAME = "h"; public static final String JODA_HOUR_24_NAME = "H"; public static final String JODA_MINUTE_OF_HOUR_NAME = "m"; public static final String JODA_SECOND_OF_MINUTE_NAME = "ss"; public static final String JODA_MILLISECOND_OF_MINUTE_NAME = "SSS"; public static final String JODA_WEEK_OF_YEAR = "w"; public static final String JODA_MONTH = "MM"; public static final String JODA_HALFDAY = "aa"; public static final String JODA_ESCAPE_CHARACTER = "'"; public static final String EMPTY_STRING = ""; static { postgresToJodaMap.put(POSTGRES_FULL_NAME_OF_DAY, JODA_FULL_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_DAY_OF_YEAR, JODA_DAY_OF_YEAR); postgresToJodaMap.put(POSTGRES_DAY_OF_MONTH, JODA_DAY_OF_MONTH); postgresToJodaMap.put(POSTGRES_DAY_OF_WEEK, JODA_DAY_OF_WEEK); postgresToJodaMap.put(POSTGRES_NAME_OF_MONTH, JODA_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_ABR_NAME_OF_MONTH, JODA_ABR_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_FULL_ERA_NAME, JODA_FULL_ERA_NAME); postgresToJodaMap.put(POSTGRES_NAME_OF_DAY, JODA_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_HOUR_12_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_12_OTHER_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_24_NAME, JODA_HOUR_24_NAME); postgresToJodaMap.put(POSTGRES_MINUTE_OF_HOUR_NAME, JODA_MINUTE_OF_HOUR_NAME); postgresToJodaMap.put(POSTGRES_SECOND_OF_MINUTE_NAME, JODA_SECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_MILLISECOND_OF_MINUTE_NAME, JODA_MILLISECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_MONTH, JODA_MONTH); postgresToJodaMap.put(POSTGRES_HALFDAY_AM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_HALFDAY_PM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_ISO_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_YEAR, JODA_YEAR); postgresToJodaMap.put(POSTGRES_ISO_1YEAR, JODA_ISO_1YEAR); postgresToJodaMap.put(POSTGRES_ISO_2YEAR, JODA_ISO_2YEAR); postgresToJodaMap.put(POSTGRES_ISO_3YEAR, JODA_ISO_3YEAR); postgresToJodaMap.put(POSTGRES_ISO_4YEAR, JODA_ISO_4YEAR); postgresToJodaMap.put(PREFIX_FM, EMPTY_STRING); postgresToJodaMap.put(PREFIX_FX, EMPTY_STRING); postgresToJodaMap.put(PREFIX_TM, EMPTY_STRING); } /** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format */ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder(pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); } /** * Length decreasing comparator. * Compares PostgresDateTimeConstant names by length, if they have the same length, compares them lexicographically. */ private static class LengthDescComparator implements Comparator { public int compare(PostgresDateTimeConstant o1, PostgresDateTimeConstant o2) { int result = o2.getName().length() - o1.getName().length(); if (result == 0) { return o1.getName().compareTo(o2.getName()); } return result; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6363 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/logical/src/main/java/org/apache/drill/common/expression/fn/JodaDateValidator.java/#L54-L256 | 2 | 645 | 6363 |
| 647 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void reset() { RepeatableIteratorWrapper changedIterator = this.changedIterator; if (changedIterator != null) { currentIterator = changedIterator; changedIteratorFieldUpdater.compareAndSet(this, changedIterator, null); } currentIterator.reset(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6374 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/UpdatableIterator.java/#L58-L66 | 1 | 647 | 6374 |
| 647 | YES I found bad smells the bad smells are: 1. Feature envy (currentIterator.reset() being called on a different object without any clear ownership or reason) 2. Long method (the method contains multiple operations and variable assignments) 3. Conditional complexity (if statement and compareAndSet() method in the same line) 4. Boolean trap (reset() method is called even if the if statement is not satisfied, leading to unnecessary operations) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void reset() { RepeatableIteratorWrapper changedIterator = this.changedIterator; if (changedIterator != null) { currentIterator = changedIterator; changedIteratorFieldUpdater.compareAndSet(this, changedIterator, null); } currentIterator.reset(); } |
feature envy | Feature envy (currentIteratorreset() being called on a different object without any clear ownership or reason)2 Long method (the method contains multiple operations and variable assignments)3 Conditional complexity (if statement and compareAndSet() method in the same line)4 Boolean trap (reset() method is called even if the if statement is not satisfied, leading to unnecessary operations) | t | f | t | leading to unnecessary operations) | 0 | 6374 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/UpdatableIterator.java/#L58-L66 | 2 | 647 | 6374 | |
| 648 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Clause getClause(Resource resource) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getDeployedVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 6380 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionResourceHeader.java/#L127-L138 | 1 | 648 | 6380 | |
| 648 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Clause getClause(Resource resource) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getDeployedVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 6380 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionResourceHeader.java/#L127-L138 | 2 | 648 | 6380 | |
| 649 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6382 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 1 | 649 | 6382 |
| 649 | YES I found bad smells the bad smells are: 1. Long method 2. Conditional complexity 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | Long method2 Conditional complexity3 Feature envy | t | f | t | 0 | 6382 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 2 | 649 | 6382 | ||
| 650 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | long method | t | t | t | 0 | 6383 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 650 | 6383 | ||
| 650 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6383 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 650 | 6383 | ||
| 651 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6384 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 651 | 6384 |
| 651 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 6384 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 651 | 6384 | |
| 652 | {"response": "YES I found bad smells. the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | 2. data class | t | t | t | 0 | 6386 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 1 | 652 | 6386 | ||
| 652 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6386 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 652 | 6386 |
| 653 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | long method | t | t | t | 0 | 6389 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 653 | 6389 | ||
| 653 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6389 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 653 | 6389 | ||
| 654 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 6390 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 654 | 6390 | |
| 656 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
data class | data class, long method | t | t | t | long method | 0 | 6405 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 1 | 656 | 6405 | |
| 656 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6405 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 2 | 656 | 6405 |
| 658 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 6413 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 2 | 658 | 6413 |
| 658 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 6413 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 1 | 658 | 6413 | |
| 659 | YES I found bad smells the bad smells are: 1. Long Constructor 2. Data class 3. Feature envy: the createJobMasterService method uses more variables from the constructor instead of its own parameters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultJobMasterServiceFactory implements JobMasterServiceFactory { private final JobMasterConfiguration jobMasterConfiguration; private final SlotPoolFactory slotPoolFactory; private final SchedulerFactory schedulerFactory; private final RpcService rpcService; private final HighAvailabilityServices haServices; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; public DefaultJobMasterServiceFactory( JobMasterConfiguration jobMasterConfiguration, SlotPoolFactory slotPoolFactory, SchedulerFactory schedulerFactory, RpcService rpcService, HighAvailabilityServices haServices, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) { this.jobMasterConfiguration = jobMasterConfiguration; this.slotPoolFactory = slotPoolFactory; this.schedulerFactory = schedulerFactory; this.rpcService = rpcService; this.haServices = haServices; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; } @Override public JobMaster createJobMasterService(JobGraph jobGraph, OnCompletionActions jobCompletionActions, ClassLoader userCodeClassloader) throws Exception { return new JobMaster( rpcService, jobMasterConfiguration, ResourceID.generate(), jobGraph, haServices, slotPoolFactory, schedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, jobCompletionActions, fatalErrorHandler, userCodeClassloader); } } |
data class | Long Constructor2 Data class3 Feature envy: the createJobMasterService method uses more variables from the constructor instead of its own parameters | t | f | t | 0 | 6424 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java/#L37-L95 | 2 | 659 | 6424 | ||
| 660 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | data class | t | t | t | 0 | 6430 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 1 | 660 | 6430 | ||
| 660 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 6430 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 2 | 660 | 6430 |
| 661 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | f | f | f | data class | 0 | 6434 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 2 | 661 | 6434 | ||
| 661 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6434 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 1 | 661 | 6434 |
| 662 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | long method | t | t | t | 0 | 6455 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 662 | 6455 | ||
| 662 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6455 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 662 | 6455 | ||
| 663 | {"message": "YES I found bad smells", "bad_smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6456 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 663 | 6456 |
| 663 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 6456 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 663 | 6456 | ||
| 667 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
data class | data class, long method | t | t | t | long method | 0 | 6549 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 1 | 667 | 6549 | |
| 667 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 6549 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 2 | 667 | 6549 |
| 670 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 6553 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 670 | 6553 |
| 670 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 6553 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 670 | 6553 |
| 671 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 6554 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 671 | 6554 | ||
| 672 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ContextMenuProvider extends MenuManager implements IMenuListener { private EditPartViewer viewer; /** * Constructs a context menu for the specified EditPartViewer. * * @param viewer * the editpart viewer */ public ContextMenuProvider(EditPartViewer viewer) { setViewer(viewer); addMenuListener(this); setRemoveAllWhenShown(true); } /** * Called when the menu is about to show. Subclasses must implement this * method to populate the menu each time it is shown. * * @param menu * this parameter is actually this object */ public abstract void buildContextMenu(IMenuManager menu); /** * Returns the EditPartViewer * * @return the viewer */ protected EditPartViewer getViewer() { return viewer; } /** * @see IMenuListener#menuAboutToShow(IMenuManager) */ public void menuAboutToShow(IMenuManager menu) { buildContextMenu(menu); } /** * Sets the editpart viewer. Called during construction. * * @param viewer * the viewer */ protected void setViewer(EditPartViewer viewer) { this.viewer = viewer; } } |
data class | long method | t | t | f | long method | data class | 0 | 6563 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.gef/src/org/eclipse/gef/ContextMenuProvider.java/#L24-L76 | 1 | 672 | 6563 |
| 672 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ContextMenuProvider extends MenuManager implements IMenuListener { private EditPartViewer viewer; /** * Constructs a context menu for the specified EditPartViewer. * * @param viewer * the editpart viewer */ public ContextMenuProvider(EditPartViewer viewer) { setViewer(viewer); addMenuListener(this); setRemoveAllWhenShown(true); } /** * Called when the menu is about to show. Subclasses must implement this * method to populate the menu each time it is shown. * * @param menu * this parameter is actually this object */ public abstract void buildContextMenu(IMenuManager menu); /** * Returns the EditPartViewer * * @return the viewer */ protected EditPartViewer getViewer() { return viewer; } /** * @see IMenuListener#menuAboutToShow(IMenuManager) */ public void menuAboutToShow(IMenuManager menu) { buildContextMenu(menu); } /** * Sets the editpart viewer. Called during construction. * * @param viewer * the viewer */ protected void setViewer(EditPartViewer viewer) { this.viewer = viewer; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6563 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.gef/src/org/eclipse/gef/ContextMenuProvider.java/#L24-L76 | 2 | 672 | 6563 |
| 674 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | long method | t | t | t | 0 | 6568 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 674 | 6568 | ||
| 674 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 6568 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 674 | 6568 | |
| 676 | YES I found bad smells the bad smells are: 1. Duplicate code (the definition of schema and value variables are repeated) 2. Feature envy (the equals method is using attributes from the SchemaAndValue class instead of its own attributes) 3. Lazy class (the class only contains basic getters and setters) 4. Long method (the toString method is long and contains multiple statements) 5. Magic number (the value null is assigned to the NULL variable without explanation) 6. Indecent exposure (the schema and value variables are defined as public) 7. Unnecessary variables (the schema and value variables could be defined directly in the constructor instead of using a temporary variable) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | Duplicate code (the definition of schema and value variables are repeated)2 Feature envy (the equals method is using attributes from the SchemaAndValue class instead of its own attributes)3 Lazy class (the class only contains basic getters and setters)4 Long method (the toString method is long and contains multiple statements)5 Magic number (the value null is assigned to the NULL variable without explanation)6 Indecent exposure (the schema and value variables are defined as public)7 Unnecessary variables (the schema and value variables could be defined directly in the constructor instead of using a temporary variable) | t | f | f | . Duplicate code (the definition of schema and value variables are repeated)2. Feature envy (the equals method is using attributes from the SchemaAndValue class instead of its own attributes)3. Lazy class (the class only contains basic getters and setters)4. Long method (the toString method is long and contains multiple statements)5. Magic number (the value null is assigned to the NULL variable without explanation)6. Indecent exposure (the schema and value variables are defined as public)7. Unnecessary variables (the schema and value variables could be defined directly in the constructor instead of using a temporary variable) | data class | 0 | 6576 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 2 | 676 | 6576 |
| 678 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } } |
data class | data class, long method | t | t | t | long method | 0 | 6584 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 | 1 | 678 | 6584 | |
| 678 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicated code 3. Feature envy 4. Long constructor 5. Temporal coupling 6. Incomplete abstraction 7. Magic numbers 8. Primitive obsession 9. Complex conditional logic 10. Data clumps 11. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } } |
data class | Long method2 Duplicated code3 Feature envy4 Long constructor5 Temporal coupling6 Incomplete abstraction7 Magic numbers8 Primitive obsession9 Complex conditional logic | t | f | f | . Long method2. Duplicated code3. Feature envy4. Long constructor5. Temporal coupling6. Incomplete abstraction7. Magic numbers8. Primitive obsession9. Complex conditional logic | data class | 0 | 6584 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 | 2 | 678 | 6584 |
| 679 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BeanIOIterator implements Iterator, Closeable { private BeanReader reader; private transient Object next; private transient Object forceNext; public BeanIOIterator(BeanReader reader) { this.reader = reader; this.next = next(); } @Override public void close() throws IOException { if (reader != null) { reader.close(); reader = null; } } @Override public boolean hasNext() { return next != null; } @Override public Object next() { Object answer = next; if (answer == null) { answer = reader.read(); // after read we may force a next if (forceNext != null) { answer = forceNext; forceNext = null; } } else { next = reader.read(); // after read we may force a next if (forceNext != null) { next = forceNext; forceNext = null; } } return answer; } @Override public void remove() { // noop } /** * Sets a custom object as the next, such as from a custom error handler */ public void setNext(Object next) { this.forceNext = next; } } |
data class | data class | t | t | t | 0 | 6586 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-beanio/src/main/java/org/apache/camel/dataformat/beanio/BeanIOIterator.java/#L25-L81 | 1 | 679 | 6586 | ||
| 679 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BeanIOIterator implements Iterator, Closeable { private BeanReader reader; private transient Object next; private transient Object forceNext; public BeanIOIterator(BeanReader reader) { this.reader = reader; this.next = next(); } @Override public void close() throws IOException { if (reader != null) { reader.close(); reader = null; } } @Override public boolean hasNext() { return next != null; } @Override public Object next() { Object answer = next; if (answer == null) { answer = reader.read(); // after read we may force a next if (forceNext != null) { answer = forceNext; forceNext = null; } } else { next = reader.read(); // after read we may force a next if (forceNext != null) { next = forceNext; forceNext = null; } } return answer; } @Override public void remove() { // noop } /** * Sets a custom object as the next, such as from a custom error handler */ public void setNext(Object next) { this.forceNext = next; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6586 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-beanio/src/main/java/org/apache/camel/dataformat/beanio/BeanIOIterator.java/#L25-L81 | 2 | 679 | 6586 |
| 681 | {"blob": false, "data_class": false, "feature_envy": false, "long_method": true} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | Incoherent response format, very different from what was expected. | f | f | f | false | 0 | 6593 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 1 | 681 | 6593 | |
| 681 | . NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 6593 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 2 | 681 | 6593 | ||
| 683 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | data class | t | t | t | 0 | 6610 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 1 | 683 | 6610 | ||
| 683 | YES I found bad smells the bad smells are: 1.Misleading indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | Misleading indentation | t | f | f | .Misleading indentation | data class | 0 | 6610 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 2 | 683 | 6610 |
| 685 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6616 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 2 | 685 | 6616 |
| 688 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
data class | long method | t | t | f | long method | data class | 0 | 6634 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 1 | 688 | 6634 |
| 688 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6634 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 2 | 688 | 6634 |
| 689 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | 1. long method | t | t | t | 0 | 6635 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 1 | 689 | 6635 | ||
| 689 | YES, I found bad smells the bad smells are: 1. Magic numbers (line 5, 6, 12, 13, 14) 2. Long method (main method) 3. Feature envy (Methods belonging to different classes but access the same data) 4. Temporary variables (row and cell) 5. Inconsistent indentation (line 3) 6. Unused code (lines 29, 30, 42, 43) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | Magic numbers (line 5, 6, | t | f | f | . Magic numbers (line 5, 6, | long method | 0 | 6635 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 2 | 689 | 6635 |
| 692 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6653 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 692 | 6653 |
| 692 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Complex conditional logic 6. Inappropriate commenting 7. Missing error handling 8. Inconsistent formatting 9. Inconsistent variable naming conventions 10. Inefficient use of string concatenation in a loop 11. Hard-coded paths and file names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Complex conditional logic6 Inappropriate commenting7 Missing error handling8 Inconsistent formatting9 Inconsistent variable naming conventions | t | f | t | 0 | 6653 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 692 | 6653 | ||
| 693 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method, data class | t | t | t | data class | 0 | 6654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 693 | 6654 | |
| 693 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Poor exception handling 5. Mixing of concerns 6. Inconsistent naming conventions 7. Immodular code 8. Unnecessary commented out code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Long method2 Feature envy3 Duplicate code4 Poor exception handling5 Mixing of concerns 6 Inconsistent naming conventions 7 Immodular code8 Unnecessary commented out code | t | f | t | 0 | 6654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 693 | 6654 | ||
| 695 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | 1. long method | t | t | t | 0 | 6659 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 695 | 6659 | ||
| 695 | YES, I found bad smells the bad smells are: 1.Long method 2. Feature envy 3. Repeating code 4. Code duplication 5. Insufficient commenting 6. Magic numbers 7. Primitive obsession 8. Inconsistent formatting 9. Unused variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method 2 Feature envy3 Repeating code4 Code duplication 5 Insufficient commenting 6 Magic numbers 7 Primitive obsession 8 Inconsistent formatting 9 Unused variables | t | f | t | 0 | 6659 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 695 | 6659 | ||
| 700 | { "error": "Unable to identify any code smells from the provided Java code." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | Not specified | f | f | f | false | 0 | 6687 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 700 | 6687 | |
| 700 | * * @param token * @param experiment * @return String * @throws RegistryServiceException */ YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 6687 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 700 | 6687 | ||
| 701 | in the Airavata Registry * * * * @param authenticationToken The token which is generated by Airavata API server * * @param gatewayId The gateway for which the new experiment should be associated with * * @param experiment Experiment Model * * @return The server-side generated experiment-model identifier * * @throws RegistryServiceException * */YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Useless comments, 5. Code duplication, 6. Exception swallowing | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Useless comments, 5 Code duplication, 6 Exception swallowing | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Useless comments, 5. Code duplication, 6. Exception swallowing | 0 | 6688 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 701 | 6688 | |
| 702 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 6697 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 702 | 6697 |
| 706 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | 1. data class | t | t | t | 0 | 6735 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 706 | 6735 | ||
| 706 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Large class 4. Long parameter list 5. Duplicated code 6. Divergent change 7. God class 8. Primitive obsession 9. Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | Long method2 Feature envy3 Large class4 Long parameter list5 Duplicated code6 Divergent change7 God class8 Primitive obsession9 Message chains | t | f | f | . Long method2. Feature envy3. Large class4. Long parameter list5. Duplicated code6. Divergent change7. God class8. Primitive obsession9. Message chains | data class | 0 | 6735 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 706 | 6735 |
| 709 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | long method | t | t | t | 0 | 6757 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 1 | 709 | 6757 | ||
| 709 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6757 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 2 | 709 | 6757 | ||
| 710 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6764 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 1 | 710 | 6764 |
| 710 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 6764 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 2 | 710 | 6764 |
| 715 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6821 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 715 | 6821 | |
| 715 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Comments as code 4. Magic numbers 5. Indecent exposure 6. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | Long method2 Duplicate code3 Comments as code4 Magic numbers5 Indecent exposure6 Feature envy | t | f | t | 0 | 6821 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 715 | 6821 | ||
| 716 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6822 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 716 | 6822 |
| 716 | YES I found bad smells the bad smells are: Feature envy, Long method, Duplicate code, Primitive obsession, Shotgun surgery, Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | Feature envy, Long method, Duplicate code, Primitive obsession, Shotgun surgery, Message chain | t | f | t | Long method, Duplicate code, Primitive obsession, Shotgun surgery, Message chain | 0 | 6822 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 716 | 6822 | |
| 717 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
long method | long method, data class | t | t | t | data class | 0 | 6826 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 1 | 717 | 6826 | |
| 717 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Use of try-with-resources blocks for unrelated classes, 5. Inconsistent indentation, 6. Lack of comments and explanatory code, 7. Lack of meaningful variable and method names, 8. Duplicate code in try-with-resources blocks, 9. Use of multiple nested try-catch blocks, 10. Use of compound assignments for complex logic. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Use of try-with-resources blocks for unrelated classes, 5 Inconsistent indentation, 6 Lack of comments and explanatory code, 7 Lack of meaningful variable and method names, 8 Duplicate code in try-with-resources blocks, 9 Use of multiple nested try-catch blocks, | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Use of try-with-resources blocks for unrelated classes, 5. Inconsistent indentation, 6. Lack of comments and explanatory code, 7. Lack of meaningful variable and method names, 8. Duplicate code in try-with-resources blocks, 9. Use of multiple nested try-catch blocks, | 0 | 6826 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 2 | 717 | 6826 | |
| 719 | {"answer": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6829 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 719 | 6829 |
| 719 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6829 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 719 | 6829 |
| 722 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | long method, data class | t | t | t | data class | 0 | 6833 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 722 | 6833 | |
| 722 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Message chain 4. Duplicated code 5. Primitive obsession 6. Lazy class 7. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Feature envy3 Message chain4 Duplicated code 5 Primitive obsession6 Lazy class7 Shotgun surgery | t | f | t | 0 | 6833 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 722 | 6833 | ||
| 723 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6834 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 723 | 6834 |
| 723 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Conditional complexity, 5. Excessive logging, 6. Unnecessary comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | Long method, 2 Feature envy, 3 Duplicate code, 4 Conditional complexity, 5 Excessive logging, 6 Unnecessary comments | t | f | t | . Long method, 3. Duplicate code, 4. Conditional complexity, 5. Excessive logging, 6. Unnecessary comments | 0 | 6834 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 723 | 6834 | |
| 728 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6853 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 728 | 6853 |
| 728 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | Long method,2 Feature envy | t | f | t | . Long method | 0 | 6853 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 728 | 6853 | |
| 729 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | long method, data class | t | t | t | data class | 0 | 6854 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 729 | 6854 | |
| 729 | YES I found bad smells1. Long method 2. Feature envy 3. Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method2 Feature envy 3 Message chain | t | f | t | 0 | 6854 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 729 | 6854 | ||
| 730 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RealRowResultSetStatistics extends RealNoPutResultSetStatistics { /* Leave these fields public for object inspectors */ public int rowsReturned; // CONSTRUCTORS /** * * */ public RealRowResultSetStatistics( int numOpens, int rowsSeen, int rowsFiltered, long constructorTime, long openTime, long nextTime, long closeTime, int resultSetNumber, int rowsReturned, double optimizerEstimatedRowCount, double optimizerEstimatedCost ) { super( numOpens, rowsSeen, rowsFiltered, constructorTime, openTime, nextTime, closeTime, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost ); this.rowsReturned = rowsReturned; } // ResultSetStatistics methods /** * Return the statement execution plan as a String. * * @param depth Indentation level. * * @return String The statement execution plan as a String. */ public String getStatementExecutionPlanText(int depth) { initFormatInfo(depth); return indent + MessageService.getTextMessage(SQLState.RTS_ROW_RS) + ":\n" + indent + MessageService.getTextMessage(SQLState.RTS_NUM_OPENS) + " = " + numOpens + "\n" + indent + MessageService.getTextMessage( SQLState.RTS_ROWS_RETURNED) + " = " + rowsReturned + "\n" + dumpTimeStats(indent, subIndent) + "\n" + dumpEstimatedCosts(subIndent) + "\n"; } /** * Return information on the scan nodes from the statement execution * plan as a String. * * @param depth Indentation level. * @param tableName if not NULL then print information for this table only * * @return String The information on the scan nodes from the * statement execution plan as a String. */ public String getScanStatisticsText(String tableName, int depth) { return ""; } // Class implementation public String toString() { return getStatementExecutionPlanText(0); } /** * Format for display, a name for this node. * */ public String getNodeName(){ return MessageService.getTextMessage(SQLState.RTS_ROW_RS); } // ----------------------------------------------------- // XPLAINable Implementation // ----------------------------------------------------- public void accept(XPLAINVisitor visitor) { // I have no children, inform my visitor about that visitor.setNumberOfChildren(0); // pre-order, depth-first traversal // me first visitor.visit(this); // I'm a leaf node, I have no children ... } public String getRSXplainType() { return XPLAINUtil.OP_ROW; } public Object getResultSetDescriptor(Object rsID, Object parentID, Object scanID, Object sortID, Object stmtID, Object timingID) { return new XPLAINResultSetDescriptor( (UUID)rsID, getRSXplainType(), getRSXplainDetails(), this.numOpens, null, // the number of index updates null, // lock mode null, // lock granularity (UUID)parentID, this.optimizerEstimatedRowCount, this.optimizerEstimatedCost, null, // the affected rows null, // the deferred rows null, // the input rows this.rowsSeen, null, // the seen rows right this.rowsFiltered, this.rowsReturned, null, // the empty right rows null, // index key optimization (UUID)scanID, (UUID)sortID, (UUID)stmtID, (UUID)timingID); } } |
data class | 1. data class | t | t | t | 0 | 6866 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/rts/RealRowResultSetStatistics.java/#L46-L187 | 1 | 730 | 6866 | ||
| 730 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RealRowResultSetStatistics extends RealNoPutResultSetStatistics { /* Leave these fields public for object inspectors */ public int rowsReturned; // CONSTRUCTORS /** * * */ public RealRowResultSetStatistics( int numOpens, int rowsSeen, int rowsFiltered, long constructorTime, long openTime, long nextTime, long closeTime, int resultSetNumber, int rowsReturned, double optimizerEstimatedRowCount, double optimizerEstimatedCost ) { super( numOpens, rowsSeen, rowsFiltered, constructorTime, openTime, nextTime, closeTime, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost ); this.rowsReturned = rowsReturned; } // ResultSetStatistics methods /** * Return the statement execution plan as a String. * * @param depth Indentation level. * * @return String The statement execution plan as a String. */ public String getStatementExecutionPlanText(int depth) { initFormatInfo(depth); return indent + MessageService.getTextMessage(SQLState.RTS_ROW_RS) + ":\n" + indent + MessageService.getTextMessage(SQLState.RTS_NUM_OPENS) + " = " + numOpens + "\n" + indent + MessageService.getTextMessage( SQLState.RTS_ROWS_RETURNED) + " = " + rowsReturned + "\n" + dumpTimeStats(indent, subIndent) + "\n" + dumpEstimatedCosts(subIndent) + "\n"; } /** * Return information on the scan nodes from the statement execution * plan as a String. * * @param depth Indentation level. * @param tableName if not NULL then print information for this table only * * @return String The information on the scan nodes from the * statement execution plan as a String. */ public String getScanStatisticsText(String tableName, int depth) { return ""; } // Class implementation public String toString() { return getStatementExecutionPlanText(0); } /** * Format for display, a name for this node. * */ public String getNodeName(){ return MessageService.getTextMessage(SQLState.RTS_ROW_RS); } // ----------------------------------------------------- // XPLAINable Implementation // ----------------------------------------------------- public void accept(XPLAINVisitor visitor) { // I have no children, inform my visitor about that visitor.setNumberOfChildren(0); // pre-order, depth-first traversal // me first visitor.visit(this); // I'm a leaf node, I have no children ... } public String getRSXplainType() { return XPLAINUtil.OP_ROW; } public Object getResultSetDescriptor(Object rsID, Object parentID, Object scanID, Object sortID, Object stmtID, Object timingID) { return new XPLAINResultSetDescriptor( (UUID)rsID, getRSXplainType(), getRSXplainDetails(), this.numOpens, null, // the number of index updates null, // lock mode null, // lock granularity (UUID)parentID, this.optimizerEstimatedRowCount, this.optimizerEstimatedCost, null, // the affected rows null, // the deferred rows null, // the input rows this.rowsSeen, null, // the seen rows right this.rowsFiltered, this.rowsReturned, null, // the empty right rows null, // index key optimization (UUID)scanID, (UUID)sortID, (UUID)stmtID, (UUID)timingID); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6866 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/rts/RealRowResultSetStatistics.java/#L46-L187 | 2 | 730 | 6866 |
| 731 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6879 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 731 | 6879 |
| 731 | YES I found bad smells the bad smells are: 1. Long method 2. Indentation smell 3. Inconsistent formatting 4. Use of switch statement 5. Nested control structures 6. Feature envy 7. Lack of comments/documentation 8. Confusing variable/parameter names 9. Potentially inefficient use of method chaining (searchStrings and toLowerCase) 10. Lack of code reusability/modularity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | Long method2 Indentation smell3 Inconsistent formatting4 Use of switch statement5 Nested control structures6 Feature envy7 Lack of comments/documentation8 Confusing variable/parameter names9 Potentially inefficient use of method chaining (searchStrings and toLowerCase) | t | f | t | 0 | 6879 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 731 | 6879 | ||
| 732 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | long method | t | t | t | 0 | 6885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 732 | 6885 | ||
| 732 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 732 | 6885 | ||
| 735 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6908 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 1 | 735 | 6908 |
| 735 | YES I found bad smells the bad smells are: 1. Unused parent class VersionedLabel 2. Using concrete class InstantiatedVersionedLabel instead of interface 3. Code duplication in constructor InstantiatedVersionedLabel() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | Unused parent class VersionedLabel2 Using concrete class InstantiatedVersionedLabel instead of interface3 Code duplication in constructor InstantiatedVersionedLabel() | t | f | f | . Unused parent class VersionedLabel2. Using concrete class InstantiatedVersionedLabel instead of interface3. Code duplication in constructor InstantiatedVersionedLabel() | data class | 0 | 6908 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 2 | 735 | 6908 |
| 739 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class CancelableThread extends Thread { protected boolean running = true; protected boolean canceled = false; public synchronized final boolean isRunning() { return running; } public synchronized final void setRunning(boolean running) { this.running = running; } /** * Subclasses shouldn't do any potentially conflicting UI work before * checking to see if the thread has been canceled. */ public synchronized final boolean isCanceled() { return canceled; } public synchronized final void cancel() { this.canceled = true; } /** * Cancels the thread given if it's running. */ public static void cancelThread(CancelableThread thread) { if ( thread != null ) { synchronized ( thread ) { if ( thread.isRunning() ) { thread.cancel(); } } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 6968 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/CancelableThread.java/#L23-L61 | 1 | 739 | 6968 |
| 739 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class CancelableThread extends Thread { protected boolean running = true; protected boolean canceled = false; public synchronized final boolean isRunning() { return running; } public synchronized final void setRunning(boolean running) { this.running = running; } /** * Subclasses shouldn't do any potentially conflicting UI work before * checking to see if the thread has been canceled. */ public synchronized final boolean isCanceled() { return canceled; } public synchronized final void cancel() { this.canceled = true; } /** * Cancels the thread given if it's running. */ public static void cancelThread(CancelableThread thread) { if ( thread != null ) { synchronized ( thread ) { if ( thread.isRunning() ) { thread.cancel(); } } } } } |
data class | f | f | f | data class | 0 | 6968 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/CancelableThread.java/#L23-L61 | 2 | 739 | 6968 | ||
| 741 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6975 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 1 | 741 | 6975 |
| 741 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 6975 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 2 | 741 | 6975 |
| 743 | { "output": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6978 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 1 | 743 | 6978 | |
| 743 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6978 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 2 | 743 | 6978 | ||
| 745 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 7007 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 745 | 7007 | |
| 745 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7007 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 745 | 7007 | |
| 747 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | 1. long method | t | t | t | 0 | 7016 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 747 | 7016 | ||
| 747 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7016 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 747 | 7016 | ||
| 748 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
data class | long method, data class | t | t | t | long method | 0 | 7018 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 1 | 748 | 7018 | |
| 748 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 7018 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 2 | 748 | 7018 |
| 749 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({"unchecked", "rawtypes"}) public final class None extends Option { private static final None INSTANCE = new None<>(); /** * Get the static instance. * @param The type of this no-value object. * @return the static instance */ public static final None getInstance() { return INSTANCE; } /** * Default constructor, does nothing. */ public None() { // super(null); // no-op } @Override public boolean hasValue() { return false; } @Override public T getValue() { throw new NoSuchElementException("None does not contain a value"); } @Override public String toString() { return "None()"; } @Override public boolean equals(Object other) { return (other == null || other.getClass() != None.class) ? false : true; } @Override public int hashCode() { return -31; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7022 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/core/src/org/apache/pivot/functional/monad/None.java/#L24-L70 | 2 | 749 | 7022 |
| 751 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JavaTimeSupplementary_es_AR extends OpenListResourceBundle { @Override protected final Object[][] getContents() { final String[] sharedAmPmMarkers = { "a.m.", "p.m.", }; final String[] sharedDatePatterns = { "GGGG y MMMM d, EEEE", "GGGG y MMMM d", "GGGG y MMM d", "dd/MM/yy G", }; final String[] sharedDayNarrows = { "d", "l", "m", "m", "j", "v", "s", }; final String[] sharedTimePatterns = { "HH:mm:ss zzzz", "HH:mm:ss z", "HH:mm:ss", "HH:mm", }; final String[] sharedJavaTimeDatePatterns = { "G y MMMM d, EEEE", "G y MMMM d", "G y MMM d", "dd/MM/yy GGGGG", }; return new Object[][] { { "field.dayperiod", "a.m./p.m." }, { "islamic.AmPmMarkers", sharedAmPmMarkers }, { "islamic.DatePatterns", sharedDatePatterns }, { "islamic.DayNarrows", sharedDayNarrows }, { "islamic.TimePatterns", sharedTimePatterns }, { "islamic.abbreviated.AmPmMarkers", sharedAmPmMarkers }, { "islamic.narrow.AmPmMarkers", sharedAmPmMarkers }, { "java.time.buddhist.DatePatterns", sharedJavaTimeDatePatterns }, { "java.time.islamic.DatePatterns", sharedJavaTimeDatePatterns }, { "java.time.roc.DatePatterns", sharedJavaTimeDatePatterns }, { "roc.AmPmMarkers", sharedAmPmMarkers }, { "roc.DatePatterns", sharedDatePatterns }, { "roc.DayNarrows", sharedDayNarrows }, { "roc.MonthAbbreviations", new String[] { "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "sep.", "oct.", "nov.", "dic.", "", } }, { "roc.MonthNarrows", new String[] { "e", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d", "", } }, { "roc.TimePatterns", sharedTimePatterns }, { "roc.abbreviated.AmPmMarkers", sharedAmPmMarkers }, { "roc.narrow.AmPmMarkers", sharedAmPmMarkers }, }; } } |
data class | Long method2 Feature envy3 Duplicate code | t | f | f | . Long method2. Feature envy3. Duplicate code | data class | 0 | 7030 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.localedata/share/classes/sun/text/resources/ext/JavaTimeSupplementary_es_AR.java/#L72-L180 | 2 | 751 | 7030 |
| 752 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 7035 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 752 | 7035 | |
| 752 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7035 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 752 | 7035 | |
| 754 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | long method | t | t | t | 0 | 7039 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 754 | 7039 | ||
| 754 | Yes, I found bad smells. the bad smells are: 1. Commented out code, 2. Long method, 3. Feature envy, 4. Duplicate code, 5. Magic numbers, 6. Conditional complexity, 7. Inconsistent naming convention, 8. Hard-coded value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | Commented out code, 2 Long method, 3 Feature envy, 4 Duplicate code, 5 Magic numbers, 6 Conditional complexity, 7 Inconsistent naming convention, 8 Hard-coded value | t | f | t | . Commented out code, 3. Feature envy, 4. Duplicate code, 5. Magic numbers, 6. Conditional complexity, 7. Inconsistent naming convention, 8. Hard-coded value. | 0 | 7039 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 754 | 7039 | |
| 755 | YES I found bad smells. the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected MqttDeliveryToken restoreToken(MqttPublish message) { final String methodName = "restoreToken"; MqttDeliveryToken token; synchronized(tokens) { String key = Integer.toString(message.getMessageId()); if (this.tokens.containsKey(key)) { token = (MqttDeliveryToken)this.tokens.get(key); //@TRACE 302=existing key={0} message={1} token={2} log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token}); } else { token = new MqttDeliveryToken(logContext); token.internalTok.setKey(key); this.tokens.put(key, token); //@TRACE 303=creating new token key={0} message={1} token={2} log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token}); } } return token; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7047 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/internal/CommsTokenStore.java/#L108-L126 | 2 | 755 | 7047 | |
| 756 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 7049 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 2 | 756 | 7049 | |
| 757 | {"message":"YES I found bad smells","bad smells are":["1. Long Method","2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 7057 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 757 | 7057 | |
| 757 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7057 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 757 | 7057 | |
| 759 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | 1. data class | t | t | t | 0 | 7066 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 1 | 759 | 7066 | ||
| 759 | YES I found bad smells. The bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | data class | 0 | 7066 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 759 | 7066 |
| 761 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | data class | t | t | t | 0 | 7110 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 1 | 761 | 7110 | ||
| 761 | YES I found bad smells.The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7110 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 2 | 761 | 7110 |
| 762 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | long method, data class | t | t | t | data class | 0 | 7113 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 762 | 7113 | |
| 762 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7113 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 762 | 7113 | |
| 764 | {"message": "YES I found bad smells", "bad smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | data class | t | t | t | 0 | 7134 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 1 | 764 | 7134 | ||
| 764 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7134 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 2 | 764 | 7134 |
| 765 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class HeaderSection extends UniformItemSection { /** {@code non-null;} the list of the one item in the section */ private final List list; /** * Constructs an instance. The file offset is initially unknown. * * @param file {@code non-null;} file that this instance is part of */ public HeaderSection(DexFile file) { super(null, file, 4); HeaderItem item = new HeaderItem(); item.setIndex(0); this.list = Collections.singletonList(item); } /** {@inheritDoc} */ @Override public IndexedItem get(Constant cst) { return null; } /** {@inheritDoc} */ @Override public Collection items() { return list; } /** {@inheritDoc} */ @Override protected void orderItems() { // Nothing to do here. } } |
data class | data class, long method | t | t | t | long method | 0 | 7136 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/HeaderSection.java/#L27-L62 | 1 | 765 | 7136 | |
| 765 | YES I found bad smells The bad smells are: 1. Magic number (4) in the constructor 2. Empty method (orderItems()) 3. Unused parameter (file) in the constructor 4. Feature envy (calling methods from HeaderItem instead of using getters) 5. Unused field (list) is never modified or accessed in the class except in the "items()" method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class HeaderSection extends UniformItemSection { /** {@code non-null;} the list of the one item in the section */ private final List list; /** * Constructs an instance. The file offset is initially unknown. * * @param file {@code non-null;} file that this instance is part of */ public HeaderSection(DexFile file) { super(null, file, 4); HeaderItem item = new HeaderItem(); item.setIndex(0); this.list = Collections.singletonList(item); } /** {@inheritDoc} */ @Override public IndexedItem get(Constant cst) { return null; } /** {@inheritDoc} */ @Override public Collection items() { return list; } /** {@inheritDoc} */ @Override protected void orderItems() { // Nothing to do here. } } |
data class | Magic number (4) in the constructor2 Empty method (orderItems())3 Unused parameter (file) in the constructor4 Feature envy (calling methods from HeaderItem instead of using getters)5 Unused field (list) is never modified or accessed in the class except in the "items()" method | t | f | f | . Magic number (4) in the constructor2. Empty method (orderItems())3. Unused parameter (file) in the constructor4. Feature envy (calling methods from HeaderItem instead of using getters)5. Unused field (list) is never modified or accessed in the class except in the "items()" method | data class | 0 | 7136 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/HeaderSection.java/#L27-L62 | 2 | 765 | 7136 |
| 766 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | long method | t | t | t | 0 | 7185 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 766 | 7185 | ||
| 766 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Primitive obsession 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method2 Duplicate code3 Primitive obsession4 Feature envy | t | f | t | 0 | 7185 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 766 | 7185 | ||
| 767 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 7227 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 767 | 7227 | |
| 767 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method2 Feature envy | t | f | t | 0 | 7227 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 767 | 7227 | ||
| 770 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void fillMenuBeforeShow(final IMenuManager manager) { manager.add(openAction); manager.add(downloadToAction); manager.add(addAttachmentAction); manager.add(deleteAttachmentAction); manager.add(new Separator()); final DownloadAttachmentOpenType preferredOpenType = DownloadAttachmentOpenType.getPreferredOpenType(); if (DownloadAttachmentOpenType.BROWSER == preferredOpenType) { manager.add(openLocallyAction); } else { manager.add(openInBrowserAction); } manager.add(copyUrlToClipboardAction); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 7268 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/wit/FileAttachmentsControl.java/#L469-L486 | 1 | 770 | 7268 |
| 770 | YES I found bad smells The bad smells are: 1. Long method 2. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void fillMenuBeforeShow(final IMenuManager manager) { manager.add(openAction); manager.add(downloadToAction); manager.add(addAttachmentAction); manager.add(deleteAttachmentAction); manager.add(new Separator()); final DownloadAttachmentOpenType preferredOpenType = DownloadAttachmentOpenType.getPreferredOpenType(); if (DownloadAttachmentOpenType.BROWSER == preferredOpenType) { manager.add(openLocallyAction); } else { manager.add(openInBrowserAction); } manager.add(copyUrlToClipboardAction); } |
feature envy | Long method 2 Code duplication | t | f | f | . Long method 2. Code duplication | feature envy | 0 | 7268 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/wit/FileAttachmentsControl.java/#L469-L486 | 2 | 770 | 7268 |
| 771 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 7278 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 771 | 7278 |
| 771 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 7278 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 771 | 7278 |
| 772 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method, data class, feature envy | t | t | t | data class, feature envy | 0 | 7285 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 772 | 7285 | |
| 772 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7285 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 772 | 7285 | ||
| 773 | YES I found bad smells the bad smells are: 1. Feature envy: The methods getIconMap(), getIcon(), and getIcons() all seem to belong more to the LocalCollection object than the FacesProperty object. 2. Duplicated code: The LocalCollection object is initialized and used multiple times in the getIconMap() and getIcons() methods. 3. Shotgun surgery: If modifications need to be made to the Text or LocalCollection objects, they will have to be made in multiple places in the code. 4. Long parameter list: The constructor for FacesProperty takes in a large number of parameters, which may make it difficult to manage and potentially lead to errors. 5. Message chains: The methods getIcon(), getIconMap(), and getIcons() all rely on calling methods from the LocalCollection object, creating a long chain of object method calls. 6. Inappropriate intimacy: The FacesProperty class has access to and manipulates objects from the Text and LocalCollection classes, which could potentially lead to tight coupling and make the code more difficult to understand and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Feature envy: The methods getIconMap(), getIcon(), and getIcons() all seem to belong more to the LocalCollection object than the FacesProperty object2 Duplicated code: The LocalCollection object is initialized and used multiple times in the getIconMap() and getIcons() methods3 Shotgun surgery: If modifications need to be made to the Text or LocalCollection objects, they will have to be made in multiple places in the code4 Long parameter list: The constructor for FacesProperty takes in a large number of parameters, which may make it difficult to manage and potentially lead to errors5 Message chains: The methods getIcon(), getIconMap(), and getIcons() all rely on calling methods from the LocalCollection object, creating a long chain of object method calls6 Inappropriate intimacy: The FacesProperty class has access to and manipulates objects from the Text and LocalCollection classes, which could potentially lead to tight coupling and make the code more difficult to understand and maintain | t | f | f | . Feature envy: The methods getIconMap(), getIcon(), and getIcons() all seem to belong more to the LocalCollection object than the FacesProperty object.2. Duplicated code: The LocalCollection object is initialized and used multiple times in the getIconMap() and getIcons() methods.3. Shotgun surgery: If modifications need to be made to the Text or LocalCollection objects, they will have to be made in multiple places in the code.4. Long parameter list: The constructor for FacesProperty takes in a large number of parameters, which may make it difficult to manage and potentially lead to errors.5. Message chains: The methods getIcon(), getIconMap(), and getIcons() all rely on calling methods from the LocalCollection object, creating a long chain of object method calls.6. Inappropriate intimacy: The FacesProperty class has access to and manipulates objects from the Text and LocalCollection classes, which could potentially lead to tight coupling and make the code more difficult to understand and maintain. | data class | 0 | 7288 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 773 | 7288 |
| 776 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | data class, long method | t | t | t | long method | 0 | 7362 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 776 | 7362 | |
| 776 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy (methods accessing and modifying fields from a different class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | Long method 2 Feature envy (methods accessing and modifying fields from a different class) | t | f | f | . Long method 2. Feature envy (methods accessing and modifying fields from a different class) | data class | 0 | 7362 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 776 | 7362 |
| 780 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7455 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 780 | 7455 | ||
| 781 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, data class | t | t | t | data class | 0 | 7457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 781 | 7457 | |
| 781 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 781 | 7457 | ||
| 782 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method | t | t | t | 0 | 7477 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 782 | 7477 | ||
| 782 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7477 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 782 | 7477 | ||
| 783 | {"response": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
long method | long method | t | t | t | 0 | 7493 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 783 | 7493 | ||
| 783 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7493 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 783 | 7493 | ||
| 784 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 7494 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 784 | 7494 |
| 784 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 7494 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 784 | 7494 | |
| 787 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | long method | t | t | t | 0 | 7509 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 1 | 787 | 7509 | ||
| 787 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7509 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 2 | 787 | 7509 | ||
| 788 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Feature envy 3. Long method 4. Data clumps 5. Lazy class 6. Shotgun surgery 7. Large class 8. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | Duplicate code 2 Feature envy 3 Long method 4 Data clumps 5 Lazy class 6 Shotgun surgery 7 Large class 8 Inappropriate Intimacy | t | f | f | . Duplicate code 2. Feature envy 3. Long method 4. Data clumps 5. Lazy class 6. Shotgun surgery 7. Large class 8. Inappropriate Intimacy | data class | 0 | 7512 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 2 | 788 | 7512 |
| 789 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7520 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 2 | 789 | 7520 |
| 790 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 7527 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 1 | 790 | 7527 | ||
| 790 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 7527 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 2 | 790 | 7527 |
| 791 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
long method | long method | t | t | t | 0 | 7535 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 791 | 7535 | ||
| 791 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7535 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 791 | 7535 | ||
| 792 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 7536 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 792 | 7536 |
| 792 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 7536 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 792 | 7536 | ||
| 794 | {"message":"YES I found bad smells","bad smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 7554 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 794 | 7554 |
| 795 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
long method | long method | t | t | t | 0 | 7555 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 1 | 795 | 7555 | ||
| 795 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Duplicate code in each case of the switch statement 4. Conditional complexity 5. Magic numbers (e.g. "yyyy" for year, "MM" for month, etc.) 6. Feature envy (each case using a different format string instead of using a single method to format the date) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
long method | Long method2 Switch statement3 Duplicate code in each case of the switch statement4 Conditional complexity5 Magic numbers (eg "yyyy" for year, "MM" for month, etc)6 Feature envy (each case using a different format string instead of using a single method to format the date) | t | f | t | "MM" for month, etc.)6. Feature envy (each case using a different format string instead of using a single method to format the date) | 0 | 7555 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 2 | 795 | 7555 | |
| 796 | {"message": "YES I found bad smells", "bad smells are": "1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 7556 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 1 | 796 | 7556 |
| 796 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 7556 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 2 | 796 | 7556 | ||
| 797 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7568 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 2 | 797 | 7568 | |
| 798 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RowReadSupport extends ReadSupport { private TypeInformation returnTypeInfo; @Override public ReadContext init(InitContext initContext) { checkNotNull(initContext, "initContext"); returnTypeInfo = ParquetSchemaConverter.fromParquetType(initContext.getFileSchema()); return new ReadContext(initContext.getFileSchema()); } @Override public RecordMaterializer prepareForRead( Configuration configuration, Map keyValueMetaData, MessageType fileSchema, ReadContext readContext) { return new RowMaterializer(readContext.getRequestedSchema(), returnTypeInfo); } } |
data class | data class, long method | t | t | t | long method | 0 | 7569 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/utils/RowReadSupport.java/#L37-L54 | 1 | 798 | 7569 | |
| 798 | YES I found bad smells the bad smells are: 1.Long method, 2.Long parameter list, 3.Inappropriate intimacy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RowReadSupport extends ReadSupport { private TypeInformation returnTypeInfo; @Override public ReadContext init(InitContext initContext) { checkNotNull(initContext, "initContext"); returnTypeInfo = ParquetSchemaConverter.fromParquetType(initContext.getFileSchema()); return new ReadContext(initContext.getFileSchema()); } @Override public RecordMaterializer prepareForRead( Configuration configuration, Map keyValueMetaData, MessageType fileSchema, ReadContext readContext) { return new RowMaterializer(readContext.getRequestedSchema(), returnTypeInfo); } } |
data class | Long method, 2Long parameter list, 3Inappropriate intimacy | t | f | f | .Long method, 2.Long parameter list, 3.Inappropriate intimacy. | data class | 0 | 7569 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/utils/RowReadSupport.java/#L37-L54 | 2 | 798 | 7569 |
| 800 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | long method | t | t | f | long method | data class | 0 | 7573 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 1 | 800 | 7573 |
| 800 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7573 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 2 | 800 | 7573 |
| 802 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
data class | long method | t | t | f | long method | data class | 0 | 7592 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 1 | 802 | 7592 |
| 802 | { "response": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 7592 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 2 | 802 | 7592 |
| 803 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Region { /** * Gets the region and state machine unique id. * * @return the region and state machine unique id */ UUID getUuid(); /** * Gets the region and state machine id. This identifier * is provided for users disposal and can be set from * a various ways to build a machines. * * @return the region and state machine id */ String getId(); /** * Start the region. */ void start(); /** * Stop the region. */ void stop(); /** * Send an event {@code E} wrapped with a {@link Message} to the region. * * @param event the wrapped event to send * @return true if event was accepted */ boolean sendEvent(Message event); /** * Send an event {@code E} to the region. * * @param event the event to send * @return true if event was accepted */ boolean sendEvent(E event); /** * Gets the current {@link State}. * * @return current state */ State getState(); /** * Gets the {@link State}s defined in this region. Returned collection is * an unmodifiable copy because states in a state machine are immutable. * * @return immutable copy of states */ Collection> getStates(); /** * Gets a {@link Transition}s for this region. * * @return immutable copy of transitions */ Collection> getTransitions(); /** * Checks if region complete. Region is considered to be completed if it has * reached its end state and no further event processing is happening. * * @return true, if complete */ boolean isComplete(); /** * Adds the state listener. * * @param listener the listener */ void addStateListener(StateMachineListener listener); /** * Removes the state listener. * * @param listener the listener */ void removeStateListener(StateMachineListener listener); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 7611 | https://github.com/spring-projects/spring-statemachine/blob/02ecb28751fcffd6f5306189f41bbcadcd3af18a/spring-statemachine-core/src/main/java/org/springframework/statemachine/region/Region.java/#L35-L123 | 1 | 803 | 7611 |
| 803 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Region { /** * Gets the region and state machine unique id. * * @return the region and state machine unique id */ UUID getUuid(); /** * Gets the region and state machine id. This identifier * is provided for users disposal and can be set from * a various ways to build a machines. * * @return the region and state machine id */ String getId(); /** * Start the region. */ void start(); /** * Stop the region. */ void stop(); /** * Send an event {@code E} wrapped with a {@link Message} to the region. * * @param event the wrapped event to send * @return true if event was accepted */ boolean sendEvent(Message event); /** * Send an event {@code E} to the region. * * @param event the event to send * @return true if event was accepted */ boolean sendEvent(E event); /** * Gets the current {@link State}. * * @return current state */ State getState(); /** * Gets the {@link State}s defined in this region. Returned collection is * an unmodifiable copy because states in a state machine are immutable. * * @return immutable copy of states */ Collection> getStates(); /** * Gets a {@link Transition}s for this region. * * @return immutable copy of transitions */ Collection> getTransitions(); /** * Checks if region complete. Region is considered to be completed if it has * reached its end state and no further event processing is happening. * * @return true, if complete */ boolean isComplete(); /** * Adds the state listener. * * @param listener the listener */ void addStateListener(StateMachineListener listener); /** * Removes the state listener. * * @param listener the listener */ void removeStateListener(StateMachineListener listener); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7611 | https://github.com/spring-projects/spring-statemachine/blob/02ecb28751fcffd6f5306189f41bbcadcd3af18a/spring-statemachine-core/src/main/java/org/springframework/statemachine/region/Region.java/#L35-L123 | 2 | 803 | 7611 |
| 804 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | long method, data class | t | t | t | data class | 0 | 7620 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 804 | 7620 | |
| 804 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 7620 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 804 | 7620 | ||
| 806 | {"message":"YES I found bad smells","detected_bad_smells":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | data class, long method | t | t | t | long method | 0 | 7625 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 1 | 806 | 7625 | |
| 806 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 7625 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 2 | 806 | 7625 |
| 809 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface IContentEmitter { String getOutputFormat( ); void initialize( IEmitterServices service ) throws BirtException; void start( IReportContent report ) throws BirtException; void end( IReportContent report ) throws BirtException; /** * start a page * * @param page */ void startPage( IPageContent page ) throws BirtException; /** * page end * * @param page */ void endPage( IPageContent page ) throws BirtException; /** * table started * * @param table */ void startTable( ITableContent table ) throws BirtException; /** * table end */ void endTable( ITableContent table ) throws BirtException; void startTableBand( ITableBandContent band ) throws BirtException; void endTableBand( ITableBandContent band ) throws BirtException; void startRow( IRowContent row ) throws BirtException; void endRow( IRowContent row ) throws BirtException; void startCell( ICellContent cell ) throws BirtException; void endCell( ICellContent cell ) throws BirtException; void startList( IListContent list ) throws BirtException; void endList( IListContent list ) throws BirtException; void startListBand( IListBandContent listBand ) throws BirtException; void endListBand( IListBandContent listBand ) throws BirtException; void startContainer( IContainerContent container ) throws BirtException; void endContainer( IContainerContent container ) throws BirtException; void startText( ITextContent text ) throws BirtException; void startData( IDataContent data ) throws BirtException; void startLabel( ILabelContent label ) throws BirtException; void startAutoText ( IAutoTextContent autoText ) throws BirtException; void startForeign( IForeignContent foreign ) throws BirtException; void startImage( IImageContent image ) throws BirtException; void startContent( IContent content ) throws BirtException; void endContent( IContent content) throws BirtException; void startGroup( IGroupContent group ) throws BirtException; void endGroup( IGroupContent group ) throws BirtException; void startTableGroup( ITableGroupContent group ) throws BirtException; void endTableGroup( ITableGroupContent group ) throws BirtException; void startListGroup( IListGroupContent group ) throws BirtException; void endListGroup( IListGroupContent group ) throws BirtException; } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7647 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/emitter/IContentEmitter.java/#L39-L126 | 2 | 809 | 7647 |
| 811 | { "response": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | data class, long method | t | t | t | long method | 0 | 7650 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 1 | 811 | 7650 | |
| 811 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7650 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 2 | 811 | 7650 |
| 814 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | data class | t | t | t | 0 | 7656 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 1 | 814 | 7656 | ||
| 814 | YES, I found bad smells. The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 7656 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 2 | 814 | 7656 |
| 815 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | data class | t | t | t | 0 | 7659 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 1 | 815 | 7659 | ||
| 815 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7659 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 2 | 815 | 7659 |
| 821 | {"response": "YES I found bad smells", "bad_smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | data class, long method | t | t | t | long method | 0 | 7686 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 1 | 821 | 7686 | |
| 821 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy. | data class | 0 | 7686 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 2 | 821 | 7686 |
| 822 | {"output": "YES, I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | 1. data class | t | t | t | 0 | 7701 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 1 | 822 | 7701 | ||
| 822 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7701 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 2 | 822 | 7701 |
| 827 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
data class | data class, long method | t | t | t | long method | 0 | 7725 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 1 | 827 | 7725 | |
| 827 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7725 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 2 | 827 | 7725 |
| 829 | {"message":"YES I found bad smells","bad_smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | 1. long method | t | t | t | 0 | 7728 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 829 | 7728 | ||
| 829 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Use of magic numbers for reader state checks 4. Use of super keyword without clear purpose/reasoning 5. Inconsistent formatting and indentation 6. Complex logic and potential for errors with multiple return statements and conditional checks within the method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | Long method2 Switch statement3 Use of magic numbers for reader state checks4 Use of super keyword without clear purpose/reasoning5 Inconsistent formatting and indentation6 Complex logic and potential for errors with multiple return statements and conditional checks within the method | t | f | t | 0 | 7728 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 829 | 7728 | ||
| 830 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | data class | t | t | t | 0 | 7736 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 1 | 830 | 7736 | ||
| 830 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7736 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 2 | 830 | 7736 |
| 834 | LFOAbstractType YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Low cohesion 4. Repeating code 5. Primitive obsession 6.Freeloader class 7.Feature envy 8. Inappropriate visibility modifier 9. Inconsistent naming convention 10. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | Long method2 Data class3 Low cohesion4 Repeating code 5 Primitive obsession 6Freeloader class 7Feature envy 8 Inappropriate visibility modifier 9 Inconsistent naming convention | t | f | t | 0 | 7749 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 2 | 834 | 7749 | ||
| 834 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | data class | t | t | t | 0 | 7749 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 1 | 834 | 7749 | ||
| 839 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 7778 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 839 | 7778 | ||
| 840 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | data class | t | t | t | 0 | 7789 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 840 | 7789 | ||
| 840 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 7789 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 840 | 7789 |
| 842 | {"response": "YES I found bad smells", "bad smells are": ["Large class", "Long method", "Feature envy", "Duplicate code"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
data class | large class, long method, feature envy, duplicate code | t | t | f | large class, long method, feature envy, duplicate code | data class | 0 | 7803 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 2 | 842 | 7803 |
| 845 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | 1: long method | t | t | t | 0 | 7823 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 845 | 7823 | ||
| 845 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7823 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 845 | 7823 | ||
| 847 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | data class | t | t | t | 0 | 7836 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 1 | 847 | 7836 | ||
| 847 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Magic number, 4. Complex conditional logic, 5. Code duplication, 6. Inconsistent naming conventions, 7. Use of global variables, 8. Use of non-descriptive variable names, 9. Use of multiple setters/getters for single variable, 10. Violation of single responsibility principle, 11. Misuse of inheritance, 12. Lack of proper comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | Long method, 2 Feature envy, 3 Magic number, 4 Complex conditional logic, 5 Code duplication, 6 Inconsistent naming conventions, 7 Use of global variables, 8 Use of non-descriptive variable names, 9 Use of multiple setters/getters for single variable, | t | f | f | . Long method, 2. Feature envy, 3. Magic number, 4. Complex conditional logic, 5. Code duplication, 6. Inconsistent naming conventions, 7. Use of global variables, 8. Use of non-descriptive variable names, 9. Use of multiple setters/getters for single variable, | data class | 0 | 7836 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 2 | 847 | 7836 |
| 850 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | data class | t | t | t | 0 | 7851 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 1 | 850 | 7851 | ||
| 850 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7851 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 850 | 7851 |
| 853 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | long method, data class | t | t | t | long method | 0 | 7877 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 853 | 7877 | |
| 853 | YES I found bad smells 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 7877 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 853 | 7877 |
| 855 | {"response": "YES I found bad smells 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugTraceBasedRegion extends AbstractTraceRegion { private final DebugTraceRegion delegate; protected DebugTraceBasedRegion(AbstractTraceRegion parent, DebugTraceRegion delegate) { super(parent); this.delegate = delegate; for (DebugTraceRegion child : delegate.getNestedRegions()) new DebugTraceBasedRegion(this, child); } private LocationData convert(DebugLocationData data) { SourceRelativeURI uri = data.getPath() != null ? new SourceRelativeURI(data.getPath()) : null; return new LocationData(data.getOffset(), data.getLength(), data.getLineNumber(), data.getEndLineNumber(), uri); } @Override public List getAssociatedLocations() { List result = Lists.newArrayListWithCapacity(delegate.getAssociations().size()); for (DebugLocationData data : delegate.getAssociations()) result.add(convert(data)); return result; } @Override public SourceRelativeURI getAssociatedSrcRelativePath() { SourceRelativeURI path = super.getAssociatedSrcRelativePath(); if (path != null) return path; return getAssociatedSrcRelativePath(delegate); } protected SourceRelativeURI getAssociatedSrcRelativePath(DebugTraceRegion region) { for (DebugLocationData associated : region.getAssociations()) { URI uri = associated.getPath(); if (uri != null) return new SourceRelativeURI(uri); } EObject container = region.eContainer(); if (container instanceof DebugTraceRegion) return getAssociatedSrcRelativePath((DebugTraceRegion) container); return null; } @Override public int getMyEndLineNumber() { return delegate.getMyEndLineNumber(); } @Override public int getMyLength() { return delegate.getMyLength(); } @Override public int getMyLineNumber() { return delegate.getMyLineNumber(); } @Override public int getMyOffset() { return delegate.getMyOffset(); } @Override public boolean isUseForDebugging() { return delegate.isUseForDebugging(); } } |
data class | Not specified | f | f | f | false | 0 | 7879 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.builder/src/org/eclipse/xtext/builder/trace/DebugTraceBasedRegion.java/#L24-L93 | 1 | 855 | 7879 | |
| 855 | YES, I found bad smells -1. Duplicated code -2. Large class -3. Long method -4. Feature envy -5. Poor naming conventions (e.g. getAssociatedLocations, getAssociatedSrcRelativePath) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugTraceBasedRegion extends AbstractTraceRegion { private final DebugTraceRegion delegate; protected DebugTraceBasedRegion(AbstractTraceRegion parent, DebugTraceRegion delegate) { super(parent); this.delegate = delegate; for (DebugTraceRegion child : delegate.getNestedRegions()) new DebugTraceBasedRegion(this, child); } private LocationData convert(DebugLocationData data) { SourceRelativeURI uri = data.getPath() != null ? new SourceRelativeURI(data.getPath()) : null; return new LocationData(data.getOffset(), data.getLength(), data.getLineNumber(), data.getEndLineNumber(), uri); } @Override public List getAssociatedLocations() { List result = Lists.newArrayListWithCapacity(delegate.getAssociations().size()); for (DebugLocationData data : delegate.getAssociations()) result.add(convert(data)); return result; } @Override public SourceRelativeURI getAssociatedSrcRelativePath() { SourceRelativeURI path = super.getAssociatedSrcRelativePath(); if (path != null) return path; return getAssociatedSrcRelativePath(delegate); } protected SourceRelativeURI getAssociatedSrcRelativePath(DebugTraceRegion region) { for (DebugLocationData associated : region.getAssociations()) { URI uri = associated.getPath(); if (uri != null) return new SourceRelativeURI(uri); } EObject container = region.eContainer(); if (container instanceof DebugTraceRegion) return getAssociatedSrcRelativePath((DebugTraceRegion) container); return null; } @Override public int getMyEndLineNumber() { return delegate.getMyEndLineNumber(); } @Override public int getMyLength() { return delegate.getMyLength(); } @Override public int getMyLineNumber() { return delegate.getMyLineNumber(); } @Override public int getMyOffset() { return delegate.getMyOffset(); } @Override public boolean isUseForDebugging() { return delegate.isUseForDebugging(); } } |
data class | Duplicated code -2 Large class -3 Long method -4 Feature envy -5 Poor naming conventions (eg getAssociatedLocations, getAssociatedSrcRelativePath) | t | f | f | . Duplicated code -2. Large class -3. Long method -4. Feature envy -5. Poor naming conventions (e.g. getAssociatedLocations, getAssociatedSrcRelativePath) | data class | 0 | 7879 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.builder/src/org/eclipse/xtext/builder/trace/DebugTraceBasedRegion.java/#L24-L93 | 2 | 855 | 7879 |
| 856 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Validator childNodeChanged(String name, NodeState before, NodeState after) throws CommitFailedException { Tree beforeTree = (parentBefore == null) ? null : parentBefore.getChild(name); Tree afterTree = parentAfter.getChild(name); if (isTokenTree(beforeTree) || isTokenTree(afterTree)) { validateTokenTree(afterTree); } else if (isTokensParent(beforeTree) || isTokensParent(afterTree)) { validateTokensParent(afterTree); } return new VisibleValidator(new TokenValidator(beforeTree, afterTree, commitInfo), true, true); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 7885 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/security/authentication/token/TokenValidatorProvider.java/#L130-L142 | 1 | 856 | 7885 | |
| 856 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic number, 3.Long parameter list, 4.Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Validator childNodeChanged(String name, NodeState before, NodeState after) throws CommitFailedException { Tree beforeTree = (parentBefore == null) ? null : parentBefore.getChild(name); Tree afterTree = parentAfter.getChild(name); if (isTokenTree(beforeTree) || isTokenTree(afterTree)) { validateTokenTree(afterTree); } else if (isTokensParent(beforeTree) || isTokensParent(afterTree)) { validateTokensParent(afterTree); } return new VisibleValidator(new TokenValidator(beforeTree, afterTree, commitInfo), true, true); } |
feature envy | Long method, 2Magic number, 3Long parameter list, 4Inappropriate intimacy | t | f | f | .Long method, 2.Magic number, 3.Long parameter list, 4.Inappropriate intimacy | feature envy | 0 | 7885 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/security/authentication/token/TokenValidatorProvider.java/#L130-L142 | 2 | 856 | 7885 |
| 857 | , I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7892 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L20095-L20123 | 2 | 857 | 7892 | ||
| 857 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7892 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L20095-L20123 | 1 | 857 | 7892 | ||
| 859 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | long method | t | t | t | 0 | 7898 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 1 | 859 | 7898 | ||
| 859 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 7898 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 2 | 859 | 7898 | |
| 861 | { "output": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are: 1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | the bad smells are: 1. long method | t | t | t | 0 | 7903 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 1 | 861 | 7903 | ||
| 861 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7903 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 2 | 861 | 7903 | ||
| 864 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | long method | t | t | f | long method | data class | 0 | 7920 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 1 | 864 | 7920 |
| 864 | opens = new Open[count]; YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7920 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 2 | 864 | 7920 |
| 866 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7932 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 866 | 7932 | ||
| 867 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | long method, data class | t | t | t | long method | 0 | 7941 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 1 | 867 | 7941 | |
| 867 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7941 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 2 | 867 | 7941 |
| 868 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 7947 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 868 | 7947 |
| 868 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Conditional complexity, 4. Long parameter list, 5. Cognitive complexity, 6. Duplicated code, 7. Data clumps. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
feature envy | Long method, 2 Feature envy, 3 Conditional complexity, 4 Long parameter list, 5 Cognitive complexity, 6 Duplicated code, 7 Data clumps | t | f | t | . Long method, 3. Conditional complexity, 4. Long parameter list, 5. Cognitive complexity, 6. Duplicated code, 7. Data clumps. | 0 | 7947 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 868 | 7947 | |
| 869 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | long method | t | t | t | 0 | 7948 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 869 | 7948 | ||
| 869 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Feature envy | t | f | t | 0 | 7948 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 869 | 7948 | ||
| 871 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7972 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 2 | 871 | 7972 |
| 872 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
long method | long method, data class | t | t | t | data class | 0 | 7980 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 1 | 872 | 7980 | |
| 872 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Duplicate code 4. Repeated logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
long method | Long method2 Long parameter list3 Duplicate code4 Repeated logic | t | f | t | 0 | 7980 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 2 | 872 | 7980 | ||
| 873 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 7982 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 1 | 873 | 7982 | |
| 873 | YES, I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Inconsistent indentation 5. Inconsistent naming conventions 6. Magic numbers 7. Useless comments 8. Unnecessary temporary variables 9. Nested conditionals 10. Coupled code 11. Strong coupling 12. Contrived complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
feature envy | Long method2 Duplicate code 3 Feature envy4 Inconsistent indentation5 Inconsistent naming conventions6 Magic numbers 7 Useless comments 8 Unnecessary temporary variables 9 Nested conditionals | t | f | t | 0 | 7982 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 2 | 873 | 7982 | ||
| 878 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | data class | t | t | t | 0 | 8012 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 1 | 878 | 8012 | ||
| 878 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8012 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 878 | 8012 |
| 879 | { "output": "YES, I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 8015 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 879 | 8015 |
| 879 | YES I found bad smells The bad smells are: 1. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | Long method | t | f | f | . Long method. | feature envy | 0 | 8015 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 879 | 8015 |
| 880 | YES I found bad smells the bad smells are: 1. Long method 2. Method parameter with different types and responsibilities (consumerHeaderKey, consumerHeaderValue, bundleClassPath) 3. The use of abbreviations (wd, dt, cv) 4. Single letter variable names (f, b, os) 5. Nested loops and conditionals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Method parameter with different types and responsibilities (consumerHeaderKey, consumerHeaderValue, bundleClassPath)3 The use of abbreviations (wd, dt, cv)4 Single letter variable names (f, b, os)5 Nested loops and conditionals | t | f | t | consumerHeaderValue, bundleClassPath)3. The use of abbreviations (wd, dt, cv)4. Single letter variable names (f, b, os)5. Nested loops and conditionals | 0 | 8016 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 880 | 8016 | |
| 882 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method | t | t | t | 0 | 8025 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 882 | 8025 | ||
| 882 | YES I found bad smells The bad smells are: 1. Long method 2. Long method (commented section discussing subtle differences) 3. Feature envy (the if statement checking the value) 4. Duplicate code (repeated code for handling null values) 5. Long parameter list 6. Long method (within the if statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method 2 Long method (commented section discussing subtle differences) 3 Feature envy (the if statement checking the value) 4 Duplicate code (repeated code for handling null values) 5 Long parameter list 6 Long method (within the if statement) | t | f | t | 0 | 8025 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 882 | 8025 | ||
| 883 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | long method | t | t | t | 0 | 8029 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 1 | 883 | 8029 | ||
| 883 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8029 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 2 | 883 | 8029 | ||
| 884 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 8035 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 1 | 884 | 8035 | |
| 884 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | Long method,2 Feature envy | t | f | t | 2. Feature envy | 0 | 8035 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 2 | 884 | 8035 | |
| 885 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 8053 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 1 | 885 | 8053 | |
| 885 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Repeated code 4. Data clump 5. Feature envy 6. Assert statements 7. Null checks 8. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | Long method2 Magic numbers3 Repeated code4 Data clump5 Feature envy6 Assert statements7 Null checks8 Incomplete error handling | t | f | t | 0 | 8053 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 2 | 885 | 8053 | ||
| 890 | {"response": "YES I found bad smells", "bad smells are": ["3. Long Method", "4. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | 3. long method, 4. data class | t | t | t | 3. long method | 0 | 8082 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 1 | 890 | 8082 | |
| 890 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8082 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 2 | 890 | 8082 |
| 891 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | long method | t | t | t | 0 | 8095 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 891 | 8095 | ||
| 891 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8095 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 891 | 8095 | ||
| 892 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8106 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 1 | 892 | 8106 |
| 892 | YES I found bad smells the bad smells are: 1.Long method, 2.Switch statement | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | Long method, 2Switch statement | t | f | f | .Long method, 2.Switch statement | feature envy | 0 | 8106 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 2 | 892 | 8106 |
| 897 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | data class | t | t | t | 0 | 8148 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 1 | 897 | 8148 | ||
| 897 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Excessive method length, 3.Long parameter list, 4.Data class, 5.Missing encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | Feature envy, 2Excessive method length, 3Long parameter list, 4Data class, 5Missing encapsulation | t | f | t | .Feature envy, 2.Excessive method length, 3.Long parameter list, 5.Missing encapsulation. | 0 | 8148 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 2 | 897 | 8148 | |
| 899 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | data class | t | t | t | 0 | 8152 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 1 | 899 | 8152 | ||
| 899 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Deprecated methods 3. Feature envy - get and set methods for private member variables 4. Long method - multiple public methods with simple logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | Magic numbers2 Deprecated methods3 Feature envy - get and set methods for private member variables4 Long method - multiple public methods with simple logic | t | f | f | . Magic numbers2. Deprecated methods3. Feature envy - get and set methods for private member variables4. Long method - multiple public methods with simple logic | data class | 0 | 8152 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 2 | 899 | 8152 |
| 900 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | 1. long method | t | t | t | 0 | 8153 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 900 | 8153 | ||
| 900 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex code 5. Multiple method calls within loops 6. Overly complex conditional statements 7. Multiple try-catch blocks with similar structure 8. Unclear variable names 9. Code repetition 10. Inconsistent formatting 11. Comments that do not add value to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method2 Feature envy3 Duplicate code4 Complex code5 Multiple method calls within loops6 Overly complex conditional statements7 Multiple try-catch blocks with similar structure8 Unclear variable names9 Code repetition | t | f | t | 0 | 8153 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 900 | 8153 | ||
| 901 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | data class, long method | t | t | t | long method | 0 | 8158 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 1 | 901 | 8158 | |
| 901 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8158 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 2 | 901 | 8158 |
| 903 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, data class | t | t | t | data class | 0 | 8170 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 903 | 8170 | |
| 904 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method | t | t | t | 0 | 8176 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 904 | 8176 | ||
| 904 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy3 Duplicate code | t | f | t | 0 | 8176 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 904 | 8176 | ||
| 908 | YES I found bad smells. The bad smells are: Feature envy, Long method, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Feature envy, Long method, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements | t | f | t | Feature envy, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements. | 0 | 8202 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 908 | 8202 | |
| 911 | { "output": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are:", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | the bad smells are:, data class | t | t | t | the bad smells are: | 0 | 8224 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 911 | 8224 | |
| 911 | YES I found bad smells the bad smells are: 1. Long class 2. Too many fields 3. Too many methods 4. Lack of encapsulation (all fields are public) 5. Inconsistent naming convention for methods 6. No comments or documentation for methods 7. Possible feature envy (excessive use of getters) 8. Lack of use of abstraction or inheritance 9. Inconsistent spacing and indentation 10. Redundant method comments (all methods have the same comment) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Long class2 Too many fields3 Too many methods4 Lack of encapsulation (all fields are public)5 Inconsistent naming convention for methods6 No comments or documentation for methods7 Possible feature envy (excessive use of getters)8 Lack of use of abstraction or inheritance 9 Inconsistent spacing and indentation | t | f | f | . Long class2. Too many fields3. Too many methods4. Lack of encapsulation (all fields are public)5. Inconsistent naming convention for methods6. No comments or documentation for methods7. Possible feature envy (excessive use of getters)8. Lack of use of abstraction or inheritance 9. Inconsistent spacing and indentation | data class | 0 | 8224 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 911 | 8224 |
| 914 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | 'Long Method', 'Data Class' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',D,a,t,a," ",C,l,a,s,s,'} | {',o,n,g," ",M,t,h,o,d,',","," ",',D,t," ",C,'} | 0 | 8245 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 914 | 8245 |
| 918 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8254 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 1 | 918 | 8254 |
| 918 | YES I found bad smells. the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 8254 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 2 | 918 | 8254 | |
| 919 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8258 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 1 | 919 | 8258 |
| 919 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8258 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 2 | 919 | 8258 | ||
| 920 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells_are": [ "Data Class", "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | bad_smells_are: data class, long method | t | t | t | long method | 0 | 8275 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 920 | 8275 | |
| 920 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8275 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 920 | 8275 |
| 922 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
long method | long method | t | t | t | 0 | 8279 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 922 | 8279 | ||
| 922 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
long method | Long method | t | f | t | 0 | 8279 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 922 | 8279 | ||
| 923 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 8280 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 923 | 8280 | |
| 923 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 8280 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 923 | 8280 | ||
| 924 | {"response": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Not specified | f | f | f | false | 0 | 8307 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 924 | 8307 | |
| 924 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8307 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 924 | 8307 | |
| 925 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | data class, long method | t | t | t | long method | 0 | 8311 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 925 | 8311 | |
| 925 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 8311 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 925 | 8311 |
| 928 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | data class | t | t | t | 0 | 8330 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 1 | 928 | 8330 | ||
| 928 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 8330 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 2 | 928 | 8330 |
| 929 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | data class | t | t | t | 0 | 8340 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 929 | 8340 | ||
| 929 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Lack of encapsulation (directly setting fields instead of using methods) 4. Mixing logic with output generation in writeAsElement method 5. Not using appropriate XMLStreamWriterHelper methods in readFromElement method 6. Hard-coded type declaration in writeAsElement method 7. Magic numbers used (e.g. 2001 for xsi) 8. Potentially redundant parameterless constructor 9. Inconsistent indentation and spacing 10. Lack of comments and/or documentation 11. Potential for null pointer exceptions with unused or unassigned fields 12. Use of multiple nested if/else statements 13. Potential for duplicate code in set methods 14. Potential for duplicated or redundant code in readFromElement method 15. Lack of error handling in readFromElement method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | Long method2 Feature envy3 Lack of encapsulation (directly setting fields instead of using methods) 4 Mixing logic with output generation in writeAsElement method 5 Not using appropriate XMLStreamWriterHelper methods in readFromElement method6 Hard-coded type declaration in writeAsElement method 7 Magic numbers used (eg 200 | t | f | f | . Long method2. Feature envy3. Lack of encapsulation (directly setting fields instead of using methods) 4. Mixing logic with output generation in writeAsElement method 5. Not using appropriate XMLStreamWriterHelper methods in readFromElement method6. Hard-coded type declaration in writeAsElement method 7. Magic numbers used (e.g. 200 | data class | 0 | 8340 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 929 | 8340 |
| 930 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 8354 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 1 | 930 | 8354 |
| 930 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8354 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 2 | 930 | 8354 | ||
| 931 | { "message": "YES, I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 8355 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 1 | 931 | 8355 | ||
| 931 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8355 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 2 | 931 | 8355 |
| 932 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | long method | t | t | t | 0 | 8357 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 1 | 932 | 8357 | ||
| 932 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Long parameter list 4. Duplicate code 5. Comments that explain bad code 6. Nested conditionals 7. Inappropriate level of abstraction 8. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | Long method2 Feature envy3 Long parameter list4 Duplicate code5 Comments that explain bad code 6 Nested conditionals7 Inappropriate level of abstraction8 Inconsistent naming conventions | t | f | t | 0 | 8357 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 2 | 932 | 8357 | ||
| 933 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | data class | t | t | t | 0 | 8372 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 1 | 933 | 8372 | ||
| 933 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 8372 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 2 | 933 | 8372 |
| 934 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | long method | t | t | t | 0 | 8390 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 1 | 934 | 8390 | ||
| 934 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 8390 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 2 | 934 | 8390 | ||
| 935 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | 1. long method | t | t | t | 0 | 8393 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 935 | 8393 | ||
| 935 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 8393 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 935 | 8393 | ||
| 936 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 8410 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 2 | 936 | 8410 |
| 938 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8427 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 938 | 8427 | |
| 939 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 8450 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 2 | 939 | 8450 |
| 940 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | long method | t | t | t | 0 | 8460 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 1 | 940 | 8460 | ||
| 940 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8460 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 2 | 940 | 8460 | |
| 941 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setContentLength(final int length) { setIntHeader("Content-Length", length); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 8463 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockHttpServletResponse.java/#L613-L617 | 1 | 941 | 8463 |
| 941 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setContentLength(final int length) { setIntHeader("Content-Length", length); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8463 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockHttpServletResponse.java/#L613-L617 | 2 | 941 | 8463 | ||
| 942 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ResultSet getUpdateVTIResultSet(NoPutResultSet source) throws StandardException { Activation activation = source.getActivation(); getAuthorizer(activation).authorize(activation, Authorizer.SQL_WRITE_OP); return new UpdateVTIResultSet(source, activation); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8465 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/GenericResultSetFactory.java/#L188-L194 | 1 | 942 | 8465 |
| 942 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ResultSet getUpdateVTIResultSet(NoPutResultSet source) throws StandardException { Activation activation = source.getActivation(); getAuthorizer(activation).authorize(activation, Authorizer.SQL_WRITE_OP); return new UpdateVTIResultSet(source, activation); } |
feature envy | Feature envy | t | f | t | 0 | 8465 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/GenericResultSetFactory.java/#L188-L194 | 2 | 942 | 8465 | ||
| 944 | YES I found bad smells the bad smells are: 1. Long Constructors: The constructors are quite long with many parameters, which could potentially make the code difficult to understand and maintain. 2. Feature Envy: Some of the methods seem to be overly accessing or manipulating data from other classes, indicating potential poor design or violation of encapsulation. 3. Large Class: The SimpleMessage class may be doing too many things and violating the Single Responsibility Principle. 4. Primitive Obsession: The class is relying on primitive data types (strings, ints, longs) instead of creating custom objects to represent those values. 5. Shotgun Surgery: Making changes to the class may require changes to multiple methods, indicating a potential violation of the Open/Closed Principle. 6. Lack of proper code organization: The methods within the class do not seem to have a clear organizational structure, making it difficult to understand the flow of the code. 7. Unnecessary comments: Some of the comments within the code may be unnecessary and not adding any value to the understanding of the code. 8. Inconsistent formatting: The code follows inconsistent formatting, making it difficult to read and understand. 9. Unnecessary duplication: The code contains some duplication, which could be refactored to improve maintainability and readability. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long Constructors: The constructors are quite long with many parameters, which could potentially make the code difficult to understand and maintain2 Feature Envy: Some of the methods seem to be overly accessing or manipulating data from other classes, indicating potential poor design or violation of encapsulation3 Large Class: The SimpleMessage class may be doing too many things and violating the Single Responsibility Principle4 Primitive Obsession: The class is relying on primitive data types (strings, ints, longs) instead of creating custom objects to represent those values5 Shotgun Surgery: Making changes to the class may require changes to multiple methods, indicating a potential violation of the Open/Closed Principle6 Lack of proper code organization: The methods within the class do not seem to have a clear organizational structure, making it difficult to understand the flow of the code7 Unnecessary comments: Some of the comments within the code may be unnecessary and not adding any value to the understanding of the code8 Inconsistent formatting: The code follows inconsistent formatting, making it difficult to read and understand9 Unnecessary duplication: The code contains some duplication, which could be refactored to improve maintainability and readability | t | f | f | . Long Constructors: The constructors are quite long with many parameters, which could potentially make the code difficult to understand and maintain.2. Feature Envy: Some of the methods seem to be overly accessing or manipulating data from other classes, indicating potential poor design or violation of encapsulation.3. Large Class: The SimpleMessage class may be doing too many things and violating the Single Responsibility Principle.4. Primitive Obsession: The class is relying on primitive data types (strings, ints, longs) instead of creating custom objects to represent those values.5. Shotgun Surgery: Making changes to the class may require changes to multiple methods, indicating a potential violation of the Open/Closed Principle.6. Lack of proper code organization: The methods within the class do not seem to have a clear organizational structure, making it difficult to understand the flow of the code.7. Unnecessary comments: Some of the comments within the code may be unnecessary and not adding any value to the understanding of the code.8. Inconsistent formatting: The code follows inconsistent formatting, making it difficult to read and understand.9. Unnecessary duplication: The code contains some duplication, which could be refactored to improve maintainability and readability. | data class | 0 | 8474 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 944 | 8474 |
| 945 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 8480 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 945 | 8480 | |
| 945 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8480 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 945 | 8480 | ||
| 946 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 8494 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 1 | 946 | 8494 |
| 946 | * @return the set of aggregated modules NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | f | f | f | feature envy | 0 | 8494 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 2 | 946 | 8494 | ||
| 947 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class, long method | t | t | t | long method | 0 | 8507 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 1 | 947 | 8507 | |
| 947 | YES I found bad smells. The bad smells are: Feature envy, Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Feature envy, Long method | t | f | f | Feature envy, Long method | data class | 0 | 8507 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 2 | 947 | 8507 |
| 949 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public void processElement(Object untypedElem) throws Exception { WindowedValue elem = (WindowedValue) untypedElem; Collection windows = windowFn.assignWindows( windowFn.new AssignContext() { @Override public T element() { return elem.getValue(); } @Override public Instant timestamp() { return elem.getTimestamp(); } @Override public BoundedWindow window() { return Iterables.getOnlyElement(elem.getWindows()); } }); WindowedValue res = WindowedValue.of(elem.getValue(), elem.getTimestamp(), windows, elem.getPane()); receiver.process(res); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8517 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/AssignWindowsParDoFnFactory.java/#L93-L120 | 2 | 949 | 8517 | ||
| 951 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 8525 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 | 1 | 951 | 8525 |
| 951 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Interrupted exception in catch block | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } } |
data class | Long method2 Feature envy3 Interrupted exception in catch block | t | f | f | . Long method2. Feature envy3. Interrupted exception in catch block | data class | 0 | 8525 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 | 2 | 951 | 8525 |
| 952 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ConfigurationInfo(CompositeData cd) { this.settings = createMap(cd.get("settings")); this.name = (String) cd.get("name"); this.label = (String) cd.get("label"); this.description = (String) cd.get("description"); this.provider = (String) cd.get("provider"); this.contents = (String) cd.get("contents"); } |
feature envy | Long method2Feature envy | t | f | t | 0 | 8527 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.management.jfr/share/classes/jdk/management/jfr/ConfigurationInfo.java/#L63-L70 | 2 | 952 | 8527 | ||
| 953 | {"message": "YES I found bad smells, the bad smells are:", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 8529 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 953 | 8529 | ||
| 953 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8529 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 953 | 8529 | ||
| 954 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 8530 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 954 | 8530 |
| 954 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8530 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 954 | 8530 | ||
| 955 | {"message":"YES I found bad smells","bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | data class | t | t | t | 0 | 8535 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 1 | 955 | 8535 | ||
| 955 | YES I found bad smells The bad smells are: 1. Mutator and Accessor methods - the class only contains getters and setters for its instance variables, which can indicate that the class is not following good object-oriented design principles. 2. Meaningless variable names - the variable names "message", "code", and "t200" do not provide enough information about what they represent, making it difficult to understand the purpose of the class. 3. Magic numbers - the code uses the number 200 multiple times, which are not clearly explained or defined. This can make the code difficult to understand and maintain. 4. Poor formatting - the code lacks proper indentation, making it difficult to read and understand. 5. No comments or documentation - there is no explanation or documentation for the purpose or functionality of the class, making it difficult for other developers to understand how to use it. 6. Lack of cohesion - the class does not have a clear and specific responsibility, making it difficult to understand its purpose and how it fits into the overall codebase. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | Mutator and Accessor methods - the class only contains getters and setters for its instance variables, which can indicate that the class is not following good object-oriented design principles2 Meaningless variable names - the variable names "message", "code", and "t200" do not provide enough information about what they represent, making it difficult to understand the purpose of the class3 Magic numbers - the code uses the number 200 multiple times, which are not clearly explained or defined This can make the code difficult to understand and maintain4 Poor formatting - the code lacks proper indentation, making it difficult to read and understand5 No comments or documentation - there is no explanation or documentation for the purpose or functionality of the class, making it difficult for other developers to understand how to use it6 Lack of cohesion - the class does not have a clear and specific responsibility, making it difficult to understand its purpose and how it fits into the overall codebase | t | f | f | . Mutator and Accessor methods - the class only contains getters and setters for its instance variables, which can indicate that the class is not following good object-oriented design principles.2. Meaningless variable names - the variable names "message", "code", and "t200" do not provide enough information about what they represent, making it difficult to understand the purpose of the class.3. Magic numbers - the code uses the number 200 multiple times, which are not clearly explained or defined. This can make the code difficult to understand and maintain.4. Poor formatting - the code lacks proper indentation, making it difficult to read and understand.5. No comments or documentation - there is no explanation or documentation for the purpose or functionality of the class, making it difficult for other developers to understand how to use it.6. Lack of cohesion - the class does not have a clear and specific responsibility, making it difficult to understand its purpose and how it fits into the overall codebase. | data class | 0 | 8535 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 2 | 955 | 8535 |
| 956 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | 1. long method | t | t | t | 0 | 8539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 956 | 8539 | ||
| 956 | YES, I found bad smells The bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 8539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 956 | 8539 |
| 957 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 8546 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 957 | 8546 |
| 957 | YES I found bad smells the bad smells are: 1. Long method 2. Message chain 3. Large class 4. Feature envy 5. Data class 6. Primitive obsession 7. Duplicate code 8. Commented-out code 9. Inappropriate naming 10. Incomplete error handling 11. Inconsistent formatting 12. Use of raw types 13. Inefficient use of constructors 14. Overuse of getters and setters 15. Use of mutable fields | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | Long method2 Message chain3 Large class4 Feature envy5 Data class6 Primitive obsession7 Duplicate code8 Commented-out code9 Inappropriate naming | t | f | t | 0 | 8546 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 957 | 8546 | ||
| 958 | { "message": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | the bad smells are: long method | t | t | t | 0 | 8556 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 958 | 8556 | ||
| 958 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8556 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 958 | 8556 | ||
| 959 | { "output": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | 1. long method | t | t | t | 0 | 8560 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 1 | 959 | 8560 | ||
| 959 | YES, I found bad smells: 1. Long method 2. Feature envy 3. Data clumps 4. Primitive obsession 5. Inconsistent naming conventions 6. Duplicate code 7. Poor exception handling 8. Tight coupling 9. Multiple responsibilities 10. Lack of proper abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | Long method2 Feature envy3 Data clumps4 Primitive obsession5 Inconsistent naming conventions6 Duplicate code7 Poor exception handling8 Tight coupling9 Multiple responsibilities | t | f | t | 0 | 8560 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 2 | 959 | 8560 | ||
| 960 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | 1. long method | t | t | t | 0 | 8567 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 960 | 8567 | ||
| 960 | YES I found bad smells - Long method, Feature envy: the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 8567 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 960 | 8567 | ||
| 961 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | long method | t | t | t | 0 | 8569 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 961 | 8569 | ||
| 961 | YES, I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Dead code 4. Feature envy 5. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method2 Duplicate code3 Dead code4 Feature envy5 Magic numbers | t | f | t | 0 | 8569 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 961 | 8569 | ||
| 962 | { "message": "YES I found bad smells", "bad smells are": [ "3. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
feature envy | 3. long method | t | t | f | 3. long method | feature envy | 0 | 8570 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 962 | 8570 |
| 962 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8570 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 962 | 8570 | ||
| 963 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | long method, data class | t | t | t | data class | 0 | 8574 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 1 | 963 | 8574 | |
| 963 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long Method 2 Feature Envy | t | f | t | 0 | 8574 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 2 | 963 | 8574 | ||
| 964 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "Long Method detected" }, { "2. Feature Envy": "Feature Envy detected" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | 1. long method: long method detected, 2. feature envy: feature envy detected | t | t | t | 2. feature envy: feature envy detected | 0 | 8595 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 1 | 964 | 8595 | |
| 964 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Logging throughout the method 5. Throwable catch-all 6. Insufficient comments/documentation 7. Multiple nested levels of code 8. Debug flag usage 9. Non-descriptive variable names 10. Commented-out code 11. Unused/unnecessary imports 12. Dependency injection used only for testing purposes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | Long method 2 Feature envy 3 Code duplication 4 Logging throughout the method 5 Throwable catch-all 6 Insufficient comments/documentation 7 Multiple nested levels of code 8 Debug flag usage 9 Non-descriptive variable names | t | f | t | 0 | 8595 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 2 | 964 | 8595 | ||
| 966 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 8633 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 1 | 966 | 8633 | |
| 966 | YES, I found bad smells 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 8633 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 2 | 966 | 8633 | ||
| 967 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | data class | t | t | t | 0 | 8646 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 967 | 8646 | ||
| 967 | YES I found bad smells the bad smells are: 1. Feature envy: The methods getExtensions(), setExtensions(), getId(), setId(), etc. are mostly accessing and manipulating the properties of the EObject class, indicating that they would be better placed within the class itself rather than as external methods. 2. Message chains: The EObject class contains multiple attributes with nested namespaces, such as extensions, id, type, version, etc., which may cause confusion and difficulty in understanding its structure and functionality. 3. Duplicated code: The methods getExtensions() and getVersion() have duplicated logic within their methods, indicating a potential need for refactoring to remove this redundancy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | Feature envy: The methods getExtensions(), setExtensions(), getId(), setId(), etc are mostly accessing and manipulating the properties of the EObject class, indicating that they would be better placed within the class itself rather than as external methods2 Message chains: The EObject class contains multiple attributes with nested namespaces, such as extensions, id, type, version, etc, which may cause confusion and difficulty in understanding its structure and functionality3 Duplicated code: The methods getExtensions() and getVersion() have duplicated logic within their methods, indicating a potential need for refactoring to remove this redundancy | t | f | f | . Feature envy: The methods getExtensions(), setExtensions(), getId(), setId(), etc. are mostly accessing and manipulating the properties of the EObject class, indicating that they would be better placed within the class itself rather than as external methods.2. Message chains: The EObject class contains multiple attributes with nested namespaces, such as extensions, id, type, version, etc., which may cause confusion and difficulty in understanding its structure and functionality.3. Duplicated code: The methods getExtensions() and getVersion() have duplicated logic within their methods, indicating a potential need for refactoring to remove this redundancy. | data class | 0 | 8646 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 967 | 8646 |
| 969 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8680 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 2 | 969 | 8680 |
| 970 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | 1. long method | t | t | t | 0 | 8695 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 970 | 8695 | ||
| 970 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | Long method2 Feature envy | t | f | t | 0 | 8695 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 970 | 8695 | ||
| 971 | { "output": "YES I found bad smells\nthe bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method | t | t | t | 0 | 8713 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 971 | 8713 | ||
| 971 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8713 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 971 | 8713 | |
| 972 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | data class | t | t | t | 0 | 8715 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 972 | 8715 | ||
| 972 | YES, I found bad smells the bad smells are: 1. Dead Code: The implementation of the IConvertible interface is empty and does not provide any functionality. 2. Accessor Mutator Pair: The get and set methods have been generated for all fields, which may be unnecessary. 3. Indecent Exposure: The fields are not declared as private, making them accessible to other classes. 4. Feature envy: The Capability class seems to be more interested in the fields of the IConvertible interface and functions only as a data class without providing any additional functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Dead Code: The implementation of the IConvertible interface is empty and does not provide any functionality2 Accessor Mutator Pair: The get and set methods have been generated for all fields, which may be unnecessary3 Indecent Exposure: The fields are not declared as private, making them accessible to other classes4 Feature envy: The Capability class seems to be more interested in the fields of the IConvertible interface and functions only as a data class without providing any additional functionality | t | f | t | . Dead Code: The implementation of the IConvertible interface is empty and does not provide any functionality.2. Accessor Mutator Pair: The get and set methods have been generated for all fields, which may be unnecessary.3. Indecent Exposure: The fields are not declared as private | 0 | 8715 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 972 | 8715 | |
| 973 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Not specified | f | f | f | false | 0 | 8773 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 973 | 8773 | |
| 973 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 8773 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 973 | 8773 | ||
| 974 | { "response": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | data class | t | t | t | 0 | 8777 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 1 | 974 | 8777 | ||
| 974 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8777 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 2 | 974 | 8777 |
| 975 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | data class | t | t | t | 0 | 8780 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 975 | 8780 | ||
| 975 | YES I found bad smells The bad smells are: 1. Getter and setter methods are unnecessary and cluttering the code. 2. Naming convention is not clear, "d" as parameter and "id" as variable name are not descriptive. 3. Class is not doing anything, no methods or logic are defined. 4. Class name "Product" is too broad and doesn't specify its purpose or responsibility. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Getter and setter methods are unnecessary and cluttering the code2 Naming convention is not clear, "d" as parameter and "id" as variable name are not descriptive3 Class is not doing anything, no methods or logic are defined4 Class name "Product" is too broad and doesn't specify its purpose or responsibility | t | f | f | . Getter and setter methods are unnecessary and cluttering the code.2. Naming convention is not clear, "d" as parameter and "id" as variable name are not descriptive.3. Class is not doing anything, no methods or logic are defined.4. Class name "Product" is too broad and doesn't specify its purpose or responsibility. | data class | 0 | 8780 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 975 | 8780 |
| 977 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | data class | t | t | t | 0 | 8825 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 1 | 977 | 8825 | ||
| 977 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 8825 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 2 | 977 | 8825 |
| 980 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | long method | t | t | f | long method | data class | 0 | 8852 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 980 | 8852 |
| 980 | YES I found bad smells the bad smells are: 1. Primitive obsession, 2. Long parameter list 3. Feature envy 4. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Primitive obsession, 2 Long parameter list3 Feature envy4 Long method | t | f | f | . Primitive obsession, 2. Long parameter list3. Feature envy4. Long method | data class | 0 | 8852 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 980 | 8852 |
| 982 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | long method | t | t | t | 0 | 8859 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 1 | 982 | 8859 | ||
| 982 | YES I found bad smells the bad smells are: 1. Long method 2. Commented out code (case DEFAULT) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | Long method2 Commented out code (case DEFAULT) | t | f | t | 0 | 8859 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 2 | 982 | 8859 | ||
| 983 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 8862 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 2 | 983 | 8862 |
| 984 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate naming conventions for variables (e.g. "v", "l", "vd") 3. Feature envy (defining a variable in a different class) 4. Use of unintuitive data types (e.g. List, Set, VarSymbol) 5. Poor code readability and organization 6. Code duplication (e.g. "vd.vartype = access(vd.vartype)") 7. Lack of comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | Long method2 Inappropriate naming conventions for variables (eg "v", "l", "vd")3 Feature envy (defining a variable in a different class)4 Use of unintuitive data types (eg List, Set, VarSymbol) 5 Poor code readability and organization 6 Code duplication (eg "vdvartype = access(vdvartype)")7 Lack of comments and documentation | t | f | t | "l", "vd")3. Feature envy (defining a variable in a different class)4. Use of unintuitive data types (e.g. List, Set, VarSymbol) 5. Poor code readability and organization 6. Code duplication (e.g. "vd.vartype = access(vd.vartype)")7. Lack of comments and documentation. | 0 | 8875 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 2 | 984 | 8875 | |
| 985 | {"output": "YES I found bad smells\n the bad smells are:\n 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | \n 1. data class | t | t | t | 0 | 8878 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 1 | 985 | 8878 | ||
| 985 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 8878 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 985 | 8878 |
| 986 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 8880 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 1 | 986 | 8880 | ||
| 986 | YES I found bad smells the bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | data class | 0 | 8880 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 2 | 986 | 8880 |
| 987 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | data class | t | t | t | 0 | 8965 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 1 | 987 | 8965 | ||
| 987 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Duplicate code2 Inconsistent naming conventions | t | f | f | . Duplicate code2. Inconsistent naming conventions | data class | 0 | 8965 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 2 | 987 | 8965 |
| 989 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9013 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 1 | 989 | 9013 |
| 989 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9013 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 2 | 989 | 9013 |
| 990 | YES I found bad smells, the bad smells are: 1. Long method, 2. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class MigrationLink { int source; int target; Migration[] migrations; public MigrationLink(int source, int target, Migration[] migrations) { this.source = source; this.target = target; this.migrations = migrations; } } |
data class | Long method, 2 Data class | t | f | t | . Long method | 0 | 9019 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java/#L113-L122 | 2 | 990 | 9019 | |
| 991 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | data class | t | t | t | 0 | 9033 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 1 | 991 | 9033 | ||
| 991 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9033 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 2 | 991 | 9033 |
| 992 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | 1. long method | t | t | t | 0 | 9038 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 992 | 9038 | ||
| 992 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9038 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 992 | 9038 | ||
| 993 | {"message": "YES I found bad smells", "bad_smells_list": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int compare(PropertyDescriptor d1, PropertyDescriptor d2) { String g1 = group(d1); String g2 = group(d2); Integer go1 = groupOrder(g1); Integer go2 = groupOrder(g2); int result = go1.compareTo(go2); if (result != 0) { return result; } result = g1.compareTo(g2); if (result != 0) { return result; } Integer po1 = propertyOrder(d1); Integer po2 = propertyOrder(d2); result = po1.compareTo(po2); if (result != 0) { return result; } return d1.getName().compareTo(d2.getName()); } |
long method | long method | t | t | t | 0 | 9070 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java/#L674-L699 | 1 | 993 | 9070 | ||
| 993 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int compare(PropertyDescriptor d1, PropertyDescriptor d2) { String g1 = group(d1); String g2 = group(d2); Integer go1 = groupOrder(g1); Integer go2 = groupOrder(g2); int result = go1.compareTo(go2); if (result != 0) { return result; } result = g1.compareTo(g2); if (result != 0) { return result; } Integer po1 = propertyOrder(d1); Integer po2 = propertyOrder(d2); result = po1.compareTo(po2); if (result != 0) { return result; } return d1.getName().compareTo(d2.getName()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9070 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java/#L674-L699 | 2 | 993 | 9070 | ||
| 995 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9092 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 2 | 995 | 9092 | |
| 996 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | long method, data class | t | t | t | data class | 0 | 9119 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 996 | 9119 | |
| 996 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Duplicate code, 5. Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Duplicate code, 5 Inconsistent naming conventions | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Duplicate code, 5. Inconsistent naming conventions. | 0 | 9119 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 996 | 9119 | |
| 997 | {"message":"YES I found bad smells","bad_smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | long method | t | t | t | 0 | 9139 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 997 | 9139 | ||
| 997 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers (SUGGEST_PLACE) 3. Repeated code 4. Code duplication (calling mLocator.getLoadStatus().name() twice) 5. Inconsistent formatting (explicitly declaring interface type in generic) 6. Feature envy (calling multiple methods from external class mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList);) 7. Nested callbacks/functional complexity 8. Hard-coded values (.name() in if statement) 9. Non-descriptive variable names (suggestionsFuture) 10. Negative conditional statements (!mLocator.getLocatorInfo().isSupportsSuggestions()) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method2 Magic numbers (SUGGEST_PLACE)3 Repeated code4 Code duplication (calling mLocatorgetLoadStatus()name() twice)5 Inconsistent formatting (explicitly declaring interface type in generic)6 Feature envy (calling multiple methods from external class mSuggestionsList = suggestionsFutureget(); showSuggestedPlaceNames(mSuggestionsList);)7 Nested callbacks/functional complexity8 Hard-coded values (name() in if statement)9 Non-descriptive variable names (suggestionsFuture) | t | f | t | 0 | 9139 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 997 | 9139 | ||
| 998 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
long method | long method | t | t | t | 0 | 9158 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 1 | 998 | 9158 | ||
| 998 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
long method | Long method2 Feature envy | t | f | t | 0 | 9158 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 2 | 998 | 9158 | ||
| 999 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | long method | t | t | t | 0 | 9162 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 999 | 9162 | ||
| 999 | "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method, 2 Feature envy" | t | f | t | 2. Feature envy." | 0 | 9162 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 999 | 9162 | |
| 1000 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | data class | t | t | f | data class | long method | 0 | 9174 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 1000 | 9174 |
| 1000 | YES, I found bad smells the bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | ) Long method2) Feature envy | t | f | t | 0 | 9174 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 1000 | 9174 | ||
| 1001 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static final class Reference { private final Tree tree; private final PropertyState property; private Reference(Tree tree, String propertyName) { this.tree = tree; this.property = tree.getProperty(propertyName); } private boolean isMultiple() { return property.isArray(); } private void setProperty(String newValue) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValue, property.getType().tag()); tree.setProperty(prop); } private void setProperty(Iterable newValues) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValues, property.getType()); tree.setProperty(prop); } } |
data class | Long method, 2 Feature envy,3 Duplicate code | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code. | data class | 0 | 9189 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java/#L548-L571 | 2 | 1001 | 9189 |
| 1003 | {"response": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | 1. long method | t | t | t | 0 | 9230 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1003 | 9230 | ||
| 1003 | Yes, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inappropriate naming convention (variable names) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy3 Inappropriate naming convention (variable names) | t | f | t | 0 | 9230 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1003 | 9230 | ||
| 1004 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | 1. long method | t | t | t | 0 | 9254 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1004 | 9254 | ||
| 1004 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9254 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1004 | 9254 | ||
| 1005 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9255 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1005 | 9255 |
| 1005 | YES I found bad smellsthe bad smells are:1. Code duplication, 2. Long method, 3. Switch statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | Code duplication, 2 Long method, 3 Switch statements | t | f | f | . Code duplication, 2. Long method, 3. Switch statements. | feature envy | 0 | 9255 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1005 | 9255 |
| 1006 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | 1. long method | t | t | t | 0 | 9258 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1006 | 9258 | ||
| 1006 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9258 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1006 | 9258 | |
| 1007 | {"message": "YES I found bad smells the bad smells are:", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9259 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1007 | 9259 |
| 1007 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 9259 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1007 | 9259 | |
| 1008 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | long method | t | t | t | 0 | 9268 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1008 | 9268 | ||
| 1008 | Yes I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method | t | f | t | 0 | 9268 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1008 | 9268 | ||
| 1009 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9269 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1009 | 9269 |
| 1009 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9269 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1009 | 9269 | ||
| 1010 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | long method | t | t | t | 0 | 9270 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1010 | 9270 | ||
| 1010 | YES, I found bad smells the bad smells are: 1 - Long method 2 - Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | - Long method2 - Feature envy | t | f | t | 0 | 9270 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1010 | 9270 | ||
| 1011 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9271 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1011 | 9271 |
| 1011 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9271 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1011 | 9271 | ||
| 1012 | { "message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void write(DataOutputView out) throws IOException { out.writeInt(position); for (int i = 0; i < position; i++) { out.writeDouble(data[i]); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9274 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/types/valuearray/DoubleValueArray.java/#L179-L186 | 1 | 1012 | 9274 |
| 1012 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void write(DataOutputView out) throws IOException { out.writeInt(position); for (int i = 0; i < position; i++) { out.writeDouble(data[i]); } } |
feature envy | Magic numbers2 Long method | t | f | f | . Magic numbers2. Long method | feature envy | 0 | 9274 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/types/valuearray/DoubleValueArray.java/#L179-L186 | 2 | 1012 | 9274 |
| 1013 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | long method, data class | t | t | t | long method | 0 | 9294 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 1013 | 9294 | |
| 1016 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | 1: long method | t | t | f | 1: long method | data class | 0 | 9303 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 1 | 1016 | 9303 |
| 1016 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9303 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 2 | 1016 | 9303 |
| 1017 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | long method, data class | t | t | t | long method | 0 | 9315 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 1 | 1017 | 9315 | |
| 1017 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9315 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 2 | 1017 | 9315 |
| 1018 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9334 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 1 | 1018 | 9334 |
| 1018 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Long method 2 Feature Envy | t | f | t | 0 | 9334 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 2 | 1018 | 9334 | ||
| 1019 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | data class, long method | t | t | t | long method | 0 | 9341 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 1019 | 9341 | |
| 1019 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy: Contains a method (getContent) that manipulates a data structure belonging to another class (List content) instead of operating on its own data. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long method2 Feature envy: Contains a method (getContent) that manipulates a data structure belonging to another class (List content) instead of operating on its own data | t | f | f | . Long method2. Feature envy: Contains a method (getContent) that manipulates a data structure belonging to another class (List content) instead of operating on its own data. | data class | 0 | 9341 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 1019 | 9341 |
| 1020 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 1020 | 9347 |
| 1020 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 1020 | 9347 | ||
| 1021 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9351 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 1 | 1021 | 9351 |
| 1021 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9351 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 2 | 1021 | 9351 |
| 1023 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 9353 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1023 | 9353 |
| 1023 | YES I found bad smells the bad smell are: 1.Feature envy (dataPlan, bestPlan) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Feature envy (dataPlan, bestPlan) | t | f | f | .Feature envy (dataPlan, bestPlan) | data class | 0 | 9353 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1023 | 9353 |
| 1025 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9360 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1025 | 9360 |
| 1025 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplicate code in switch statement 5. Nested if/else statements 6. Poor variable naming 7. Potential for NullPointerException | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | Long method2 Feature envy3 Magic numbers4 Duplicate code in switch statement5 Nested if/else statements 6 Poor variable naming 7 Potential for NullPointerException | t | f | t | 0 | 9360 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1025 | 9360 | ||
| 1026 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 9361 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1026 | 9361 | ||
| 1026 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy (multiple occurrences of using the same object's methods/properties) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method2 Duplicate code3 Feature envy (multiple occurrences of using the same object's methods/properties) | t | f | t | 0 | 9361 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1026 | 9361 | ||
| 1027 | {"message": "YES I found bad smells", "bad smells are": "1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | 1. long method | t | t | t | 0 | 9370 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1027 | 9370 | ||
| 1027 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Lack of comments 4. Primitive obsession 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method 2 Duplicate code 3 Lack of comments 4 Primitive obsession 5 Feature envy | t | f | t | 0 | 9370 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1027 | 9370 | ||
| 1028 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Primitive Obsession/Code duplication 4. Inconsistent Formatting/Inconsistent Naming Conventions 5. Poor exception handling 6. Lack of Comments/Documentation 7. Magic Numbers/Unreadable code 8. Poor Control Flow/Inconsistent Use of Logic Operators 9. Data Clumps 10. Shotgun Surgery 11. Inappropriate Error Messages/System.out use 12. Continual Redundancy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | Long Method2 Feature Envy 3 Primitive Obsession/Code duplication 4 Inconsistent Formatting/Inconsistent Naming Conventions 5 Poor exception handling 6 Lack of Comments/Documentation 7 Magic Numbers/Unreadable code 8 Poor Control Flow/Inconsistent Use of Logic Operators 9 Data Clumps | t | f | t | 0 | 9371 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1028 | 9371 | ||
| 1029 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 9382 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1029 | 9382 | |
| 1029 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Nested loops and conditionals 4. Lack of proper abstraction and encapsulation 5. Inefficient use of Java 8 Streams 6. Use of HashMaps instead of more appropriate data structures 7. Code duplication 8. Unnecessary use of lambdas and method references | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
feature envy | Long method2 Feature envy3 Nested loops and conditionals4 Lack of proper abstraction and encapsulation5 Inefficient use of Java 8 Streams6 Use of HashMaps instead of more appropriate data structures7 Code duplication8 Unnecessary use of lambdas and method references | t | f | t | 0 | 9382 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1029 | 9382 | ||
| 1030 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method | t | t | t | 0 | 9383 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1030 | 9383 | ||
| 1030 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9383 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1030 | 9383 | |
| 1031 | { "error": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method | t | t | t | 0 | 9386 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1031 | 9386 | ||
| 1031 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Useless comments (ex: "@Override @MultiMQAdminCmdMethod") 4. Use of multiple catch statements for different exceptions 5. Nested for loops and try-catch statements 6. Repeated code (ex: calling mqAdminExt.resetOffsetByTimestamp twice) 7. Poor variable naming (ex: groupRollbackStats, rollbackStats, rollbackStatsMap, rollbackStatsList) 8. Lack of encapsulation/abstraction (ex: direct access to class attributes) 9. Use of Maps and Lists instead of more object-oriented data structures 10. Nested if-else statements 11. Use of continue statement to skip code (ex: "continue;" in the catch block) 12. Lack of exception handling techniques like throwing/catching custom exceptions 13. Lack of separation of concerns (resetOffset method has multiple responsibilities) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy3 Useless comments (ex: "@Override @MultiMQAdminCmdMethod")4 Use of multiple catch statements for different exceptions5 Nested for loops and try-catch statements6 Repeated code (ex: calling mqAdminExtresetOffsetByTimestamp twice)7 Poor variable naming (ex: groupRollbackStats, rollbackStats, rollbackStatsMap, rollbackStatsList)8 Lack of encapsulation/abstraction (ex: direct access to class attributes)9 Use of Maps and Lists instead of more object-oriented data structures | t | f | t | rollbackStats, rollbackStatsMap, rollbackStatsList)8. Lack of encapsulation/abstraction (ex: direct access to class attributes)9. Use of Maps and Lists instead of more object-oriented data structures | 0 | 9386 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1031 | 9386 | |
| 1032 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
feature envy | Not specified | f | f | f | false | 0 | 9387 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1032 | 9387 | |
| 1032 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9387 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1032 | 9387 | ||
| 1033 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | long method | t | t | t | 0 | 9391 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1033 | 9391 | ||
| 1033 | YES I found bad smells The bad smells are: 1. Long method 2. Exception throwing (multiple exceptions in method signature) 3. Dependency on specific library (java.util.concurrent) 4. Inconsistent variable naming conventions 5. Multiple nested if statements 6. Lack of comments or documentation explaining the purpose of the method and its parameters 7. Possible synchronization issues (using wait() without a corresponding notify() or notifyAll()) 8. Code duplication (using the same code to check for internalFuture and to calculate remaining time) 9. Hard to read and understand code flow due to excessive use of ternary operator (? and :) 10. Magic numbers (1, TimeUnit.MILLISECONDS) used without explanation or context. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method2 Exception throwing (multiple exceptions in method signature)3 Dependency on specific library (javautilconcurrent)4 Inconsistent variable naming conventions5 Multiple nested if statements6 Lack of comments or documentation explaining the purpose of the method and its parameters7 Possible synchronization issues (using wait() without a corresponding notify() or notifyAll())8 Code duplication (using the same code to check for internalFuture and to calculate remaining time)9 Hard to read and understand code flow due to excessive use of ternary operator (? and :) | t | f | t | 0 | 9391 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1033 | 9391 | ||
| 1034 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 9396 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 2 | 1034 | 9396 | ||
| 1035 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 1 | 1035 | 9397 | ||
| 1035 | of the bad smells are present in the code. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 2 | 1035 | 9397 | ||
| 1036 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | data class | t | t | t | 0 | 9403 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 1 | 1036 | 9403 | ||
| 1036 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 9403 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 2 | 1036 | 9403 |
| 1038 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | long method | t | t | t | 0 | 9410 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 1 | 1038 | 9410 | ||
| 1038 | YES, I found bad smells. The bad smells are: 1. Long method 2. Repeated code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | Long method2 Repeated code3 Feature envy | t | f | t | 0 | 9410 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 2 | 1038 | 9410 | ||
| 1041 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | long method | t | t | t | 0 | 9429 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 1041 | 9429 | ||
| 1041 | YES I found bad smells The bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy. | 0 | 9429 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 1041 | 9429 | |
| 1042 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | long method | t | t | t | 0 | 9438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 1042 | 9438 | ||
| 1042 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 1042 | 9438 | ||
| 1043 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | 1. long method | t | t | t | 0 | 9446 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1043 | 9446 | ||
| 1043 | YES I found bad smells the bad smells are: Long method, Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Long method, Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | t | f | t | Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | 0 | 9446 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1043 | 9446 | |
| 1044 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9447 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1044 | 9447 |
| 1044 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (multiple lines creating and setting preferred feature rendering modes) 4. Magic numbers (hard-coded values for viewpoint locations and durations) 5. Hard-coded URLs for service feature tables 6. Nested if statements with no descriptive comments 7. Use of double && in conditional statements instead of using nested if/else statements 8. Use of arrays to add operational layers instead of using a more efficient data structure such as a list 9. Catch-all exception handling with no specific exception types included 10. Lack of error handling or validation for user input or potential errors in code 11. Lack of meaningful variable names (e.g. mapViewTop, mapViewBottom) 12. Use of mutable public fields instead of private fields with getters and setters 13. Multi-purpose method with no clear separation of concerns or functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
feature envy | Long method2 Feature envy3 Duplicate code (multiple lines creating and setting preferred feature rendering modes)4 Magic numbers (hard-coded values for viewpoint locations and durations)5 Hard-coded URLs for service feature tables6 Nested if statements with no descriptive comments 7 Use of double && in conditional statements instead of using nested if/else statements 8 Use of arrays to add operational layers instead of using a more efficient data structure such as a list 9 Catch-all exception handling with no specific exception types included | t | f | t | 0 | 9447 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1044 | 9447 | ||
| 1045 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 9454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 1045 | 9454 | ||
| 1045 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 1045 | 9454 | ||
| 1046 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9456 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1046 | 9456 | |
| 1047 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 9457 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1047 | 9457 | |
| 1047 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 9457 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1047 | 9457 | |
| 1049 | { "message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9463 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1049 | 9463 |
| 1049 | YES I found bad smells the bad smells are: 1. Method with a long code block 2. Repeated calls to getValueAccessorById() 3. Repeated calls to getValueVectorId() 4. AllocationHelper being used twice without any logic or condition 5. Non-descriptive variable names (e.g. fragmentIdVector) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | Method with a long code block2 Repeated calls to getValueAccessorById()3 Repeated calls to getValueVectorId()4 AllocationHelper being used twice without any logic or condition5 Non-descriptive variable names (eg fragmentIdVector) | t | f | f | . Method with a long code block2. Repeated calls to getValueAccessorById()3. Repeated calls to getValueVectorId()4. AllocationHelper being used twice without any logic or condition5. Non-descriptive variable names (e.g. fragmentIdVector) | feature envy | 0 | 9463 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1049 | 9463 |
| 1050 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | long method | t | t | t | 0 | 9476 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1050 | 9476 | ||
| 1050 | YES I found bad smells the bad smells are: 1.Long method 2.Long method 3.Unnecessary comments 4.Lack of proper indentation/formatting 5.Lack of proper variable naming 6.Feature envy 7.Magic numbers/strings used in code 8.Manually handling exceptions instead of using try-catch blocks 9.Accessing properties multiple times instead of storing them in a variable 10.Multiple nested if-else statements 11.Missing error handling for exceptions 12.Hard-coded class and method names instead of using reflection 13.Large number of method calls 14.Methods performing multiple actions instead of a single, specific task. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Long method2Long method3Unnecessary comments4Lack of proper indentation/formatting5Lack of proper variable naming6Feature envy7Magic numbers/strings used in code8Manually handling exceptions instead of using try-catch blocks9Accessing properties multiple times instead of storing them in a variable | t | f | t | 0 | 9476 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1050 | 9476 | ||
| 1051 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9477 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1051 | 9477 |
| 1051 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Long parameter list", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
feature envy | long method, long parameter list, feature envy | t | t | t | long method, long parameter list | 0 | 9477 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1051 | 9477 | |
| 1052 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | data class | t | t | t | 0 | 9479 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 1 | 1052 | 9479 | ||
| 1052 | YES, I found bad smells the bad smells are: 1. Empty default constructor 2. Lack of encapsulation and direct manipulation of private data fields through getters and setters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | Empty default constructor2 Lack of encapsulation and direct manipulation of private data fields through getters and setters | t | f | f | . Empty default constructor2. Lack of encapsulation and direct manipulation of private data fields through getters and setters | data class | 0 | 9479 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 2 | 1052 | 9479 |
| 1053 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | long method | t | t | t | 0 | 9480 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 1 | 1053 | 9480 | ||
| 1053 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: next(), interceptors, interceptor.getInstance(), interceptor.getMethod(), LifecycleInvocation, InterceptorInvocation, operation.equals(), method.getParameterTypes(), InvocationContext.getTimer(), BeanInvocation, target, method, methodParameters, parameters 3. Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4. Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5. Magic numbers: the code contains integer values (e.g. 1 and 0) without any explanation or clear purpose, making it difficult to understand 6. Lack of comments: there are no comments in the code explaining the purpose or logic behind certain decisions or methods, making it difficult for future developers to understand 7. Poor naming conventions: variable names such as "next" and "method" are not descriptive enough, making it difficult to understand their purpose and usage | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | Long method2 Feature envy: next(), interceptors, interceptorgetInstance(), interceptorgetMethod(), LifecycleInvocation, InterceptorInvocation, operationequals(), methodgetParameterTypes(), InvocationContextgetTimer(), BeanInvocation, target, method, methodParameters, parameters3 Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4 Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5 Magic numbers: the code contains integer values (eg | t | f | t | interceptors, interceptor.getInstance(), interceptor.getMethod(), LifecycleInvocation, InterceptorInvocation, operation.equals(), method.getParameterTypes(), InvocationContext.getTimer(), BeanInvocation, target, method, methodParameters, parameters3. Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4. Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5. Magic numbers: the code contains integer values (e.g. | 0 | 9480 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 2 | 1053 | 9480 | |
| 1058 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | long method | t | t | t | 0 | 9520 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1058 | 9520 | ||
| 1058 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Use of temporary variables 5. Exception handling inside a loop 6. Use of constant strings instead of enums 7. Use of raw types in collections 8. Use of multiple try-catch blocks with similar code 9. Poor exception handling (only logging the exception) 10. Lack of comments or documentation for complex logic and data structures. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy3 Duplicated code4 Use of temporary variables5 Exception handling inside a loop6 Use of constant strings instead of enums7 Use of raw types in collections8 Use of multiple try-catch blocks with similar code9 Poor exception handling (only logging the exception) | t | f | t | 0 | 9520 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1058 | 9520 | ||
| 1059 | { "output": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | data class | t | t | t | 0 | 9530 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 1 | 1059 | 9530 | ||
| 1059 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 9530 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 2 | 1059 | 9530 |
| 1062 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | data class | t | t | t | 0 | 9545 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 1 | 1062 | 9545 | ||
| 1062 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 9545 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 2 | 1062 | 9545 |
| 1063 | { "message": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Long Method" }, { "2": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | 1: long method, 2: data class | t | t | t | 2: data class | 0 | 9551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 1 | 1063 | 9551 | |
| 1063 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 2 | 1063 | 9551 | ||
| 1064 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | 1. data class | t | t | t | 0 | 9556 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 1 | 1064 | 9556 | ||
| 1064 | YES I found bad smells The bad smells are: 1. Misleading variable names - key and val are not clear descriptors of the purpose of these variables. 2. Lack of encapsulation - the variables are declared as public instead of private and not accessed through setter or getter methods. 3. Code duplication - the methods getEncodedKey() and getEncodedValue() have similar functionality and could be refactored into a single method. 4. Primitive obsession - the class only contains primitive type variables and could benefit from using a more complex data type or creating a separate class. 5. Possible feature envy - the encode() method is not a part of the Header class and could potentially be moved to a different class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | Misleading variable names - key and val are not clear descriptors of the purpose of these variables2 Lack of encapsulation - the variables are declared as public instead of private and not accessed through setter or getter methods3 Code duplication - the methods getEncodedKey() and getEncodedValue() have similar functionality and could be refactored into a single method4 Primitive obsession - the class only contains primitive type variables and could benefit from using a more complex data type or creating a separate class5 Possible feature envy - the encode() method is not a part of the Header class and could potentially be moved to a different class | t | f | f | . Misleading variable names - key and val are not clear descriptors of the purpose of these variables.2. Lack of encapsulation - the variables are declared as public instead of private and not accessed through setter or getter methods.3. Code duplication - the methods getEncodedKey() and getEncodedValue() have similar functionality and could be refactored into a single method.4. Primitive obsession - the class only contains primitive type variables and could benefit from using a more complex data type or creating a separate class.5. Possible feature envy - the encode() method is not a part of the Header class and could potentially be moved to a different class. | data class | 0 | 9556 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 2 | 1064 | 9556 |
| 1065 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | Not specified | f | f | f | false | 0 | 9567 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 1 | 1065 | 9567 | |
| 1065 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | Long Method 2 Feature Envy | t | f | f | . Long Method 2. Feature Envy | data class | 0 | 9567 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 2 | 1065 | 9567 |
| 1067 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | long method | t | t | f | long method | data class | 0 | 9582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 1067 | 9582 |
| 1067 | YES I found bad smells The bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 9582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1067 | 9582 |
| 1072 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | 1. data class | t | t | t | 0 | 9608 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 1 | 1072 | 9608 | ||
| 1072 | YES I found bad smells the bad smells are: 1. Feature envy: The EnsemblExonVO class extends EnsemblDBBaseVO, indicating a potential use of attributes and methods from the parent class, which could lead to feature envy. 2. Duplicate code: The get and set methods for version, assemblyName, seqRegionName, and strand are all similar with only the attribute names being different, indicating a potential for duplicate code. 3. Long class: The EnsemblExonVO class contains only attributes and get/set methods, making it a relatively large and potentially bloated class. 4. Inappropriate naming: The name "EnsemblExonVO" does not accurately describe the purpose of the class and its attributes. 5. Inconsistent formatting: The use of both annotations and getter/setter methods to specify JSON properties is inconsistent and could lead to confusion or potential errors. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | Feature envy: The EnsemblExonVO class extends EnsemblDBBaseVO, indicating a potential use of attributes and methods from the parent class, which could lead to feature envy2 Duplicate code: The get and set methods for version, assemblyName, seqRegionName, and strand are all similar with only the attribute names being different, indicating a potential for duplicate code3 Long class: The EnsemblExonVO class contains only attributes and get/set methods, making it a relatively large and potentially bloated class4 Inappropriate naming: The name "EnsemblExonVO" does not accurately describe the purpose of the class and its attributes5 Inconsistent formatting: The use of both annotations and getter/setter methods to specify JSON properties is inconsistent and could lead to confusion or potential errors | t | f | f | . Feature envy: The EnsemblExonVO class extends EnsemblDBBaseVO, indicating a potential use of attributes and methods from the parent class, which could lead to feature envy.2. Duplicate code: The get and set methods for version, assemblyName, seqRegionName, and strand are all similar with only the attribute names being different, indicating a potential for duplicate code.3. Long class: The EnsemblExonVO class contains only attributes and get/set methods, making it a relatively large and potentially bloated class.4. Inappropriate naming: The name "EnsemblExonVO" does not accurately describe the purpose of the class and its attributes.5. Inconsistent formatting: The use of both annotations and getter/setter methods to specify JSON properties is inconsistent and could lead to confusion or potential errors. | data class | 0 | 9608 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 2 | 1072 | 9608 |
| 1074 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 9629 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 1074 | 9629 |
| 1076 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Hard-coded string values 5. Nested looping 6. Duplicate code 7. Use of mutable data types without proper synchronization | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long method2 Feature envy3 Commented out code4 Hard-coded string values5 Nested looping6 Duplicate code7 Use of mutable data types without proper synchronization | t | f | t | 0 | 9643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 1076 | 9643 | ||
| 1078 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | 1. long method | t | t | t | 0 | 9647 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1078 | 9647 | ||
| 1078 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9647 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1078 | 9647 | ||
| 1081 | { "output": "YES I found bad smells, the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | 1. data class | t | t | t | 0 | 9680 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 1081 | 9680 | ||
| 1081 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy. | data class | 0 | 9680 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 1081 | 9680 |
| 1082 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSystemFactoryBean implements InitializingBean, DisposableBean, FactoryBean { private FileSystem fs; private Configuration configuration; private URI uri; private String user; private boolean closeAll = false; private boolean close = true; public void afterPropertiesSet() throws Exception { Configuration cfg = (configuration != null ? configuration : new Configuration(true)); if (uri == null) { uri = FileSystem.getDefaultUri(cfg); } if (StringUtils.hasText(user)) { fs = FileSystem.get(uri, cfg, user); } else { fs = FileSystem.get(uri, cfg); } } public void destroy() throws Exception { if (fs != null && close) { fs.close(); } fs = null; if (closeAll) { // TODO: potentially call close all just for the current user FileSystem.closeAll(); } } public FileSystem getObject() throws Exception { return fs; } public Class getObjectType() { return (fs != null ? fs.getClass() : FileSystem.class); } public boolean isSingleton() { return true; } /** * Sets the Hadoop configuration for this file system. * * @param configuration The configuration to set. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * Sets the URI (if available) for this file system. * * @param uri The uri to set. */ public void setUri(URI uri) { this.uri = uri; } /** * Sets the user impersonation (optional) for creating this file-system. * Should be used when running against a Hadoop Kerberos cluster. * * @param user user/group information */ public void setUser(String user) { this.user = user; } /** * Indicates whether all the Hadoop file systems should be closed once this factory is destroyed. * False by default - should be turned on as a safety measure when the app controls the entire lifecycle of Hadoop inside * a JVM. * * @param closeAll the close all * @see FileSystem#closeAll() */ public void setCloseAll(boolean closeAll) { this.closeAll = closeAll; } /** * Indicates whether the Hadoop file systems should be closed once this factory is destroyed. * True by default - should be turned off when running 'embedded' or if long running operations outlive the application context. * * @param close close * @see FileSystem#close() */ public void setClose(boolean close) { this.close = close; } } |
data class | data class | t | t | t | 0 | 9684 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-hadoop-core/src/main/java/org/springframework/data/hadoop/fs/FileSystemFactoryBean.java/#L34-L131 | 1 | 1082 | 9684 | ||
| 1082 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSystemFactoryBean implements InitializingBean, DisposableBean, FactoryBean { private FileSystem fs; private Configuration configuration; private URI uri; private String user; private boolean closeAll = false; private boolean close = true; public void afterPropertiesSet() throws Exception { Configuration cfg = (configuration != null ? configuration : new Configuration(true)); if (uri == null) { uri = FileSystem.getDefaultUri(cfg); } if (StringUtils.hasText(user)) { fs = FileSystem.get(uri, cfg, user); } else { fs = FileSystem.get(uri, cfg); } } public void destroy() throws Exception { if (fs != null && close) { fs.close(); } fs = null; if (closeAll) { // TODO: potentially call close all just for the current user FileSystem.closeAll(); } } public FileSystem getObject() throws Exception { return fs; } public Class getObjectType() { return (fs != null ? fs.getClass() : FileSystem.class); } public boolean isSingleton() { return true; } /** * Sets the Hadoop configuration for this file system. * * @param configuration The configuration to set. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * Sets the URI (if available) for this file system. * * @param uri The uri to set. */ public void setUri(URI uri) { this.uri = uri; } /** * Sets the user impersonation (optional) for creating this file-system. * Should be used when running against a Hadoop Kerberos cluster. * * @param user user/group information */ public void setUser(String user) { this.user = user; } /** * Indicates whether all the Hadoop file systems should be closed once this factory is destroyed. * False by default - should be turned on as a safety measure when the app controls the entire lifecycle of Hadoop inside * a JVM. * * @param closeAll the close all * @see FileSystem#closeAll() */ public void setCloseAll(boolean closeAll) { this.closeAll = closeAll; } /** * Indicates whether the Hadoop file systems should be closed once this factory is destroyed. * True by default - should be turned off when running 'embedded' or if long running operations outlive the application context. * * @param close close * @see FileSystem#close() */ public void setClose(boolean close) { this.close = close; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9684 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-hadoop-core/src/main/java/org/springframework/data/hadoop/fs/FileSystemFactoryBean.java/#L34-L131 | 2 | 1082 | 9684 |
| 1083 | YES I found bad smells. The bad smells are: 1. Long class 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | Long class2 Long method3 Feature envy | t | f | f | . Long class2. Long method3. Feature envy | data class | 0 | 9689 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 1083 | 9689 |
| 1084 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void createServerIdEditGroup( Composite parent ) { // ServerID Group Group serverIdGroup = BaseWidgetUtils.createGroup( parent, "ServerID input", 1 ); GridLayout serverIdGroupGridLayout = new GridLayout( 2, false ); serverIdGroup.setLayout( serverIdGroupGridLayout ); serverIdGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // ServerID Text BaseWidgetUtils.createLabel( serverIdGroup, "ID:", 1 ); idText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // URL Text BaseWidgetUtils.createLabel( serverIdGroup, "URL:", 1 ); urlText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); urlText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9692 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ServerIdDialog.java/#L239-L256 | 1 | 1084 | 9692 |
| 1084 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void createServerIdEditGroup( Composite parent ) { // ServerID Group Group serverIdGroup = BaseWidgetUtils.createGroup( parent, "ServerID input", 1 ); GridLayout serverIdGroupGridLayout = new GridLayout( 2, false ); serverIdGroup.setLayout( serverIdGroupGridLayout ); serverIdGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // ServerID Text BaseWidgetUtils.createLabel( serverIdGroup, "ID:", 1 ); idText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // URL Text BaseWidgetUtils.createLabel( serverIdGroup, "URL:", 1 ); urlText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); urlText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9692 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ServerIdDialog.java/#L239-L256 | 2 | 1084 | 9692 | ||
| 1089 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @WeakOuter final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } |
data class | long method, data class | t | t | t | long method | 0 | 9716 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java/#L1049-L1101 | 1 | 1089 | 9716 | |
| 1089 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication (use of similar code in multiple methods) 4. Use of abbreviations (e.g. "mc" for "modCount", "e" for "element") that make the code less readable 5. Redundant code (e.g. checking for null "action" parameter in forEach() method when it is already checked in the spliterator() method) 6. Non-descriptive variable names (e.g. "e" for "element", "mc" for "modCount") 7. Mixing of responsibilities (e.g. the EntrySet class is responsible for both containing entries and detecting concurrent modifications) 8. Unused or redundant comments (e.g. the comment above forEach() method) 9. Use of non-standard formatting conventions (e.g. use of "_" in variable names, lack of indentation) 10. Lack of error handling for possible NullPointerException in some methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @WeakOuter final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } |
data class | Long method2 Feature envy3 Code duplication (use of similar code in multiple methods)4 Use of abbreviations (eg "mc" for "modCount", "e" for "element") that make the code less readable5 Redundant code (eg checking for null "action" parameter in forEach() method when it is already checked in the spliterator() method)6 Non-descriptive variable names (eg "e" for "element", "mc" for "modCount")7 Mixing of responsibilities (eg the EntrySet class is responsible for both containing entries and detecting concurrent modifications)8 Unused or redundant comments (eg the comment above forEach() method)9 Use of non-standard formatting conventions (eg use of "_" in variable names, lack of indentation) | t | f | f | . Long method2. Feature envy3. Code duplication (use of similar code in multiple methods)4. Use of abbreviations (e.g. "mc" for "modCount", "e" for "element") that make the code less readable5. Redundant code (e.g. checking for null "action" parameter in forEach() method when it is already checked in the spliterator() method)6. Non-descriptive variable names (e.g. "e" for "element", "mc" for "modCount")7. Mixing of responsibilities (e.g. the EntrySet class is responsible for both containing entries and detecting concurrent modifications)8. Unused or redundant comments (e.g. the comment above forEach() method)9. Use of non-standard formatting conventions (e.g. use of "_" in variable names, lack of indentation) | data class | 0 | 9716 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java/#L1049-L1101 | 2 | 1089 | 9716 |
| 1090 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9724 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 1 | 1090 | 9724 |
| 1090 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9724 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 2 | 1090 | 9724 | ||
| 1091 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Collection collectBasePaths(Iterable targets) { return StreamSupport.stream(targets.spliterator(), false) .map(BuildTarget::getBasePath) .collect(ImmutableSet.toImmutableSet()); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9728 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/core/model/impl/InMemoryBuildFileTree.java/#L71-L75 | 1 | 1091 | 9728 |
| 1091 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Collection collectBasePaths(Iterable targets) { return StreamSupport.stream(targets.spliterator(), false) .map(BuildTarget::getBasePath) .collect(ImmutableSet.toImmutableSet()); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 9728 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/core/model/impl/InMemoryBuildFileTree.java/#L71-L75 | 2 | 1091 | 9728 | ||
| 1093 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XelatexRunner extends LatexRunner { /** * Create a new ProgramRunner. */ public XelatexRunner() { super(); } protected String getWindowsProgramName() { return "xelatex.exe"; } protected String getUnixProgramName() { return "xelatex"; } public String getDescription() { return "XeLatex program"; } /** * Enable SyncTeX */ public String getDefaultArguments() { return "-synctex=1 "+super.getDefaultArguments(); } /** * @return output file format (pdf) */ public String getOutputFormat() { return TexlipseProperties.OUTPUT_FORMAT_PDF; } } |
data class | data class | t | t | t | 0 | 9748 | https://github.com/eclipse/texlipse/blob/1bc72f856d4144ad0bc9baaa9575457bd7b68e1a/org.eclipse.texlipse/source/org/eclipse/texlipse/builder/XelatexRunner.java/#L20-L55 | 1 | 1093 | 9748 | ||
| 1093 | YES I found bad smells 1. Long method: The class XelatexRunner contains multiple methods, each with a different purpose, making it a long and potentially confusing class to maintain. 2. Duplicate code: The methods getWindowsProgramName() and getUnixProgramName() have similar implementation, indicating possible code duplication. 3. Feature envy: The method getOutputFormat() uses a constant from a different class, indicating a possible feature envy. 4. Inappropriate naming: The class name XelatexRunner does not accurately represent its purpose, as it extends a more general class (LatexRunner). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XelatexRunner extends LatexRunner { /** * Create a new ProgramRunner. */ public XelatexRunner() { super(); } protected String getWindowsProgramName() { return "xelatex.exe"; } protected String getUnixProgramName() { return "xelatex"; } public String getDescription() { return "XeLatex program"; } /** * Enable SyncTeX */ public String getDefaultArguments() { return "-synctex=1 "+super.getDefaultArguments(); } /** * @return output file format (pdf) */ public String getOutputFormat() { return TexlipseProperties.OUTPUT_FORMAT_PDF; } } |
data class | Long method: The class XelatexRunner contains multiple methods, each with a different purpose, making it a long and potentially confusing class to maintain2 Duplicate code: The methods getWindowsProgramName() and getUnixProgramName() have similar implementation, indicating possible code duplication3 Feature envy: The method getOutputFormat() uses a constant from a different class, indicating a possible feature envy4 Inappropriate naming: The class name XelatexRunner does not accurately represent its purpose, as it extends a more general class (LatexRunner) | t | f | f | . Long method: The class XelatexRunner contains multiple methods, each with a different purpose, making it a long and potentially confusing class to maintain.2. Duplicate code: The methods getWindowsProgramName() and getUnixProgramName() have similar implementation, indicating possible code duplication.3. Feature envy: The method getOutputFormat() uses a constant from a different class, indicating a possible feature envy.4. Inappropriate naming: The class name XelatexRunner does not accurately represent its purpose, as it extends a more general class (LatexRunner). | data class | 0 | 9748 | https://github.com/eclipse/texlipse/blob/1bc72f856d4144ad0bc9baaa9575457bd7b68e1a/org.eclipse.texlipse/source/org/eclipse/texlipse/builder/XelatexRunner.java/#L20-L55 | 2 | 1093 | 9748 |
| 1095 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
feature envy | the bad smells are: long method, data class | t | t | f | the bad smells are: long method, data class | feature envy | 0 | 9781 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 1 | 1095 | 9781 |
| 1095 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 9781 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 2 | 1095 | 9781 | |
| 1097 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Lack of encapsulation 6. Use of public fields in the builder 7. Lack of error handling and validation in the builder 8. Inconsistent formatting and spacing 9. Use of null for optional values 10. Lack of documentation and comments 11. Possible violation of single responsibility principle with the inner class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | Long method2 Feature envy 3 Code duplication 4 Inconsistent naming conventions 5 Lack of encapsulation 6 Use of public fields in the builder 7 Lack of error handling and validation in the builder 8 Inconsistent formatting and spacing 9 Use of null for optional values | t | f | f | . Long method2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Lack of encapsulation 6. Use of public fields in the builder 7. Lack of error handling and validation in the builder 8. Inconsistent formatting and spacing 9. Use of null for optional values | data class | 0 | 9800 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 2 | 1097 | 9800 |
| 1098 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9825 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 1098 | 9825 |
| 1099 | {"response": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | 1. data class | t | t | t | 0 | 9827 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 1 | 1099 | 9827 | ||
| 1099 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9827 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 2 | 1099 | 9827 |
| 1100 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void processRTTmeasurement(long measuredRTT, Exchange exchange, int retransmissionCount){ //System.out.println("Measured an RTT of " + measuredRTT + " after using " + retransmissionCount + " retries." ); RemoteEndpoint endpoint = getRemoteEndpoint(exchange); int rtoType = endpoint.getExchangeEstimatorState(exchange); // The basic rto algorithm does not care for the blind estimator, set weak/strong to false endpoint.setBlindStrong(false); endpoint.setBlindWeak(false); //Perform normal update of the RTO updateEstimator(measuredRTT, rtoType, endpoint); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9830 | https://github.com/eclipse/californium/blob/0dd6db579be90c514dd765027ec55ed7a4668337/californium-core/src/main/java/org/eclipse/californium/core/network/stack/congestioncontrol/BasicRto.java/#L40-L52 | 1 | 1100 | 9830 |
| 1100 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void processRTTmeasurement(long measuredRTT, Exchange exchange, int retransmissionCount){ //System.out.println("Measured an RTT of " + measuredRTT + " after using " + retransmissionCount + " retries." ); RemoteEndpoint endpoint = getRemoteEndpoint(exchange); int rtoType = endpoint.getExchangeEstimatorState(exchange); // The basic rto algorithm does not care for the blind estimator, set weak/strong to false endpoint.setBlindStrong(false); endpoint.setBlindWeak(false); //Perform normal update of the RTO updateEstimator(measuredRTT, rtoType, endpoint); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9830 | https://github.com/eclipse/californium/blob/0dd6db579be90c514dd765027ec55ed7a4668337/californium-core/src/main/java/org/eclipse/californium/core/network/stack/congestioncontrol/BasicRto.java/#L40-L52 | 2 | 1100 | 9830 |
| 1101 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9839 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1101 | 9839 | ||
| 1102 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9840 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1102 | 9840 |
| 1102 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9840 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1102 | 9840 | ||
| 1103 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | 1. long method | t | t | t | 0 | 9847 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1103 | 9847 | ||
| 1103 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9847 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1103 | 9847 | ||
| 1106 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 9879 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 1106 | 9879 | |
| 1106 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9879 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 1106 | 9879 | ||
| 1108 | {"answer": "YES I found bad smells", "bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TableAliasImpl extends SQLSyntaxElementBase implements TableAlias { private final String _tableAlias; private final ColumnNameList _columnAliases; public TableAliasImpl( SQLProcessorAggregator processor, String tableAlias, ColumnNameList columnNames ) { this( processor, TableAlias.class, tableAlias, columnNames ); } protected TableAliasImpl( SQLProcessorAggregator processor, Class implementingClass, String tableAlias, ColumnNameList columnNames ) { super( processor, implementingClass ); Objects.requireNonNull( tableAlias, "table alias table name" ); this._tableAlias = tableAlias; this._columnAliases = columnNames; } public ColumnNameList getColumnAliases() { return this._columnAliases; } public String getTableAlias() { return this._tableAlias; } @Override protected boolean doesEqual( TableAlias another ) { return this._tableAlias.equals( another.getTableAlias() ) && bothNullOrEquals( this._columnAliases, another.getColumnAliases() ); } } |
data class | data class, long method | t | t | t | long method | 0 | 9882 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/libraries/sql-generator/src/main/java/org/apache/polygene/library/sql/generator/implementation/grammar/query/TableAliasImpl.java/#L31-L68 | 1 | 1108 | 9882 | |
| 1108 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TableAliasImpl extends SQLSyntaxElementBase implements TableAlias { private final String _tableAlias; private final ColumnNameList _columnAliases; public TableAliasImpl( SQLProcessorAggregator processor, String tableAlias, ColumnNameList columnNames ) { this( processor, TableAlias.class, tableAlias, columnNames ); } protected TableAliasImpl( SQLProcessorAggregator processor, Class implementingClass, String tableAlias, ColumnNameList columnNames ) { super( processor, implementingClass ); Objects.requireNonNull( tableAlias, "table alias table name" ); this._tableAlias = tableAlias; this._columnAliases = columnNames; } public ColumnNameList getColumnAliases() { return this._columnAliases; } public String getTableAlias() { return this._tableAlias; } @Override protected boolean doesEqual( TableAlias another ) { return this._tableAlias.equals( another.getTableAlias() ) && bothNullOrEquals( this._columnAliases, another.getColumnAliases() ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9882 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/libraries/sql-generator/src/main/java/org/apache/polygene/library/sql/generator/implementation/grammar/query/TableAliasImpl.java/#L31-L68 | 2 | 1108 | 9882 |
| 1109 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | data class, long method | t | t | t | long method | 0 | 9883 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 1 | 1109 | 9883 | |
| 1109 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9883 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 2 | 1109 | 9883 |
| 1111 | Yes I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9888 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 2 | 1111 | 9888 | ||
| 1112 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 9894 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 1 | 1112 | 9894 | ||
| 1112 | YES, I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 9894 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 2 | 1112 | 9894 |
| 1114 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9896 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 1114 | 9896 |
| 1114 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9896 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 1114 | 9896 | ||
| 1116 | { "output": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Data class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 9954 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 1 | 1116 | 9954 | |
| 1116 | YES I found bad smells the bad smells are: 1. Duplicated code (DEFAULT_MAX_RETRIES_ON_DELETE, DEFAULT_MAX_RETRIES_ON_TOUCH) 2. Long method (toString()) 3. Shotgun surgery (changing and setting multiple variables in different methods) 4. Magic numbers (arbitrary values like -1, 10) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | Duplicated code (DEFAULT_MAX_RETRIES_ON_DELETE, DEFAULT_MAX_RETRIES_ON_TOUCH)2 Long method (toString())3 Shotgun surgery (changing and setting multiple variables in different methods)4 Magic numbers (arbitrary values like - | t | f | f | . Duplicated code (DEFAULT_MAX_RETRIES_ON_DELETE, DEFAULT_MAX_RETRIES_ON_TOUCH)2. Long method (toString())3. Shotgun surgery (changing and setting multiple variables in different methods)4. Magic numbers (arbitrary values like - | data class | 0 | 9954 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 2 | 1116 | 9954 |
| 1117 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | long method | t | t | t | 0 | 9955 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1117 | 9955 | ||
| 1117 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional statements 5. Nested loops 6. Long parameter list 7. Tight coupling 8. Non-descriptive variable naming 9. Redundant code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | Long method2 Feature envy3 Duplicate code4 Complex conditional statements5 Nested loops6 Long parameter list7 Tight coupling8 Non-descriptive variable naming9 Redundant code | t | f | t | 0 | 9955 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1117 | 9955 | ||
| 1118 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 9959 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1118 | 9959 | ||
| 1118 | YES I found bad smells -the bad smells are: 1. Commented out code (lines 51-61) 2. Long method (lines 1-74) 3. Repeated code (lines 17-31 and lines 34-47) 4. Use of a "catch-all" Exception handler (line 18) 5. Conditional complexity (lines 17-47) 6. Method with multiple responsibilities (lines 1-74) 7. Inconsistent naming conventions for variables and methods (e.g. regionOrigin and regionExtent) 8. Magic numbers (lines 67 and 74) 9. Lack of proper error handling (e.g. returning null instead of throwing an exception) 10. Use of deprecated methods (e.g. Util.toLowerInvariant on line 65) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Commented out code (lines 5 | t | f | f | . Commented out code (lines 5 | long method | 0 | 9959 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1118 | 9959 |
| 1119 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9960 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1119 | 9960 |
| 1119 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9960 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1119 | 9960 | ||
| 1120 | {"message": "YES I found bad smells: the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9974 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 1 | 1120 | 9974 |
| 1120 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9974 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 2 | 1120 | 9974 |
| 1123 | {"answer": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | data class, long method | t | t | t | long method | 0 | 9994 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 1123 | 9994 | |
| 1123 | YES I found bad smells The bad smells are: 1. Empty default constructor 2. Mutable fields (incomplete and items) 3. Getters and setters for every field, violating encapsulation principle 4. Poor naming of class and fields, not following camelCase naming convention 5. Lack of comments and documentation 6. No methods or functionality defined in the class, rendering it useless | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Empty default constructor2 Mutable fields (incomplete and items)3 Getters and setters for every field, violating encapsulation principle4 Poor naming of class and fields, not following camelCase naming convention5 Lack of comments and documentation6 No methods or functionality defined in the class, rendering it useless | t | f | f | . Empty default constructor2. Mutable fields (incomplete and items)3. Getters and setters for every field, violating encapsulation principle4. Poor naming of class and fields, not following camelCase naming convention5. Lack of comments and documentation6. No methods or functionality defined in the class, rendering it useless | data class | 0 | 9994 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 1123 | 9994 |
| 1124 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10000 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 1 | 1124 | 10000 | |
| 1124 | YES, I found bad smells. the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | Feature envy | t | f | t | 0 | 10000 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 2 | 1124 | 10000 | ||
| 1125 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10003 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 1125 | 10003 | |
| 1125 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | Long method | t | f | t | 0 | 10003 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 1125 | 10003 | ||
| 1129 | {"response": "YES I found bad smells - the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean hasCmpPersistenceUnit(final Persistence persistence) { for (final PersistenceUnit unit : persistence.getPersistenceUnit()) { if (unit.getName().startsWith("cmp")) { return true; } } return false; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10016 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/config/OutputGeneratedDescriptors.java/#L173-L180 | 1 | 1129 | 10016 |
| 1129 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean hasCmpPersistenceUnit(final Persistence persistence) { for (final PersistenceUnit unit : persistence.getPersistenceUnit()) { if (unit.getName().startsWith("cmp")) { return true; } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10016 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/config/OutputGeneratedDescriptors.java/#L173-L180 | 2 | 1129 | 10016 | ||
| 1130 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | long method, data class | t | t | t | long method | 0 | 10018 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 1 | 1130 | 10018 | |
| 1130 | Yes, bad smells I found are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10018 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 2 | 1130 | 10018 |
| 1132 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static ConcurrentCompositeConfiguration createLocalConfig() { MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); if (localConfig.size() > 0) { ConfigModel model = new ConfigModel(); model.setConfig(localConfig); loader.getConfigModels().add(model); } LOGGER.info("create local config:"); for (ConfigModel configModel : loader.getConfigModels()) { LOGGER.info(" {}.", configModel.getUrl()); } ConcurrentCompositeConfiguration config = ConfigUtil.createLocalConfig(loader.getConfigModels()); ConfigUtil.setMicroserviceConfigLoader(config, loader); return config; } |
long method | 1. long method | t | t | t | 0 | 10040 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigUtil.java/#L105-L122 | 1 | 1132 | 10040 | ||
| 1132 | YES I found bad smells. the bad smells are: 1. Long method, 2. Repetitive code, 3. Feature envy, 4. Poor variable naming, 5. Poor use of static methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static ConcurrentCompositeConfiguration createLocalConfig() { MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); if (localConfig.size() > 0) { ConfigModel model = new ConfigModel(); model.setConfig(localConfig); loader.getConfigModels().add(model); } LOGGER.info("create local config:"); for (ConfigModel configModel : loader.getConfigModels()) { LOGGER.info(" {}.", configModel.getUrl()); } ConcurrentCompositeConfiguration config = ConfigUtil.createLocalConfig(loader.getConfigModels()); ConfigUtil.setMicroserviceConfigLoader(config, loader); return config; } |
long method | Long method, 2 Repetitive code, 3 Feature envy, 4 Poor variable naming, 5 Poor use of static methods | t | f | t | 2. Repetitive code, 3. Feature envy, 4. Poor variable naming, 5. Poor use of static methods. | 0 | 10040 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigUtil.java/#L105-L122 | 2 | 1132 | 10040 | |
| 1133 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 10042 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 | 1 | 1133 | 10042 |
| 1133 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Duplicate code 5. Magic numbers 6. Inconsistent formatting and naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } } |
data class | Long method2 Feature envy3 Commented out code4 Duplicate code5 Magic numbers6 Inconsistent formatting and naming conventions | t | f | f | . Long method2. Feature envy3. Commented out code4. Duplicate code5. Magic numbers6. Inconsistent formatting and naming conventions | data class | 0 | 10042 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 | 2 | 1133 | 10042 |
| 1134 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | data class | t | t | t | 0 | 10054 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 1 | 1134 | 10054 | ||
| 1134 | YES I found bad smells The bad smells are: 1. Feature envy: The methods getName(), isPrimitive(), getValue(), and getType() all use the jdiVariable object extensively, indicating that they may be better suited for the JdbVariable class itself. 2. Long parameter list: The constructor for JdbVariable has two parameters which could potentially be condensed into one object for better organization. 3. Inconsistent naming conventions: Some variables are named with a prefix of "jdi" while others are not, indicating a lack of consistency in naming conventions. 4. Lack of comments: There are no comments or explanatory comments in the code, making it difficult to understand for other developers. 5. Use of ternary operator: The ternary operator used in the constructor for value can be confusing and could potentially be rewritten for better readability. 6. Redundant code: The constructor for JdbVariable could potentially be combined with the second constructor by setting a default value for the jdiVariable parameter. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | Feature envy: The methods getName(), isPrimitive(), getValue(), and getType() all use the jdiVariable object extensively, indicating that they may be better suited for the JdbVariable class itself2 Long parameter list: The constructor for JdbVariable has two parameters which could potentially be condensed into one object for better organization3 Inconsistent naming conventions: Some variables are named with a prefix of "jdi" while others are not, indicating a lack of consistency in naming conventions4 Lack of comments: There are no comments or explanatory comments in the code, making it difficult to understand for other developers5 Use of ternary operator: The ternary operator used in the constructor for value can be confusing and could potentially be rewritten for better readability6 Redundant code: The constructor for JdbVariable could potentially be combined with the second constructor by setting a default value for the jdiVariable parameter | t | f | f | . Feature envy: The methods getName(), isPrimitive(), getValue(), and getType() all use the jdiVariable object extensively, indicating that they may be better suited for the JdbVariable class itself.2. Long parameter list: The constructor for JdbVariable has two parameters which could potentially be condensed into one object for better organization.3. Inconsistent naming conventions: Some variables are named with a prefix of "jdi" while others are not, indicating a lack of consistency in naming conventions.4. Lack of comments: There are no comments or explanatory comments in the code, making it difficult to understand for other developers.5. Use of ternary operator: The ternary operator used in the constructor for value can be confusing and could potentially be rewritten for better readability.6. Redundant code: The constructor for JdbVariable could potentially be combined with the second constructor by setting a default value for the jdiVariable parameter. | data class | 0 | 10054 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 2 | 1134 | 10054 |
| 1136 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method | t | t | t | 0 | 10058 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 1 | 1136 | 10058 | ||
| 1136 | YES I found bad smells the bad smells are: 1. long method, 2. feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method, 2 feature envy | t | f | t | 2. feature envy | 0 | 10058 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 2 | 1136 | 10058 | |
| 1137 | { "output": "YES, I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
data class | "YES, I found bad smells", "the bad smells are" | t | f | f | "YES, I found bad smells", "the bad smells are" | data class | 0 | 10065 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 1 | 1137 | 10065 |
| 1137 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Repeated code in getters and setters"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
data class | long method, repeated code in getters and setters | t | t | f | long method, repeated code in getters and setters | data class | 0 | 10065 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 2 | 1137 | 10065 |
| 1138 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | data class | t | t | t | 0 | 10070 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1138 | 10070 | ||
| 1138 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10070 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1138 | 10070 |
| 1139 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | data class | t | t | t | 0 | 10076 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 1 | 1139 | 10076 | ||
| 1139 | YES I found bad smells the bad smells are: 1. Inconsistent naming convention - the class name "Roles" is not consistent with the variable name "roles". 2. Incomplete constructor - the default constructor is not used and only one parameterized constructor is provided. 3. Missing access modifiers - the access modifiers for the class and methods are not specified explicitly. 4. Magic number - the namespace string is hard-coded as a magic number instead of being defined as a constant or variable. 5. Unused variable - the parameterized constructor takes in a "roles" parameter but it is not used in the constructor or anywhere else in the class. 6. Lack of encapsulation - the roles field is public and can be accessed and modified directly. 7. Feature envy - the getRoles() method is returning the "roles" field instead of just accessing it directly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | Inconsistent naming convention - the class name "Roles" is not consistent with the variable name "roles" 2 Incomplete constructor - the default constructor is not used and only one parameterized constructor is provided 3 Missing access modifiers - the access modifiers for the class and methods are not specified explicitly 4 Magic number - the namespace string is hard-coded as a magic number instead of being defined as a constant or variable 5 Unused variable - the parameterized constructor takes in a "roles" parameter but it is not used in the constructor or anywhere else in the class 6 Lack of encapsulation - the roles field is public and can be accessed and modified directly 7 Feature envy - the getRoles() method is returning the "roles" field instead of just accessing it directly | t | f | f | . Inconsistent naming convention - the class name "Roles" is not consistent with the variable name "roles". 2. Incomplete constructor - the default constructor is not used and only one parameterized constructor is provided. 3. Missing access modifiers - the access modifiers for the class and methods are not specified explicitly. 4. Magic number - the namespace string is hard-coded as a magic number instead of being defined as a constant or variable. 5. Unused variable - the parameterized constructor takes in a "roles" parameter but it is not used in the constructor or anywhere else in the class. 6. Lack of encapsulation - the roles field is public and can be accessed and modified directly. 7. Feature envy - the getRoles() method is returning the "roles" field instead of just accessing it directly. | data class | 0 | 10076 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 2 | 1139 | 10076 |
| 1140 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10089 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 2 | 1140 | 10089 | ||
| 1141 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10090 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 1 | 1141 | 10090 |
| 1141 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10090 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 2 | 1141 | 10090 | |
| 1142 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | long method | t | t | t | 0 | 10095 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 1 | 1142 | 10095 | ||
| 1142 | YES I found bad smells * 1. Long method * 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | Long method* 2 Feature envy | t | f | t | 0 | 10095 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 2 | 1142 | 10095 | ||
| 1145 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | long method | t | t | t | 0 | 10111 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 1145 | 10111 | ||
| 1145 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10111 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 1145 | 10111 | ||
| 1147 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | long method, data class | t | t | t | data class | 0 | 10122 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1147 | 10122 | |
| 1147 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10122 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1147 | 10122 | ||
| 1150 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | \n1. data class | t | t | t | 0 | 10131 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 1150 | 10131 | ||
| 1150 | YES I found bad smells the bad smells are: 1. Long interface containing 25 methods and 11 constants. 2. Feature envy between MetricsIndexerSource and BaseSource. 3. Duplicate code in method names and descriptions related to different operations. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | Long interface containing 25 methods and | t | f | f | . Long interface containing 25 methods and | data class | 0 | 10131 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 1150 | 10131 |
| 1152 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 10133 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 1152 | 10133 | |
| 1152 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10133 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 1152 | 10133 | |
| 1154 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10137 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 1154 | 10137 | |
| 1154 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10137 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 1154 | 10137 | |
| 1155 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
feature envy | the bad smells are: long method | t | t | f | the bad smells are: long method | feature envy | 0 | 10138 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 1155 | 10138 |
| 1155 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Inconsistent naming, 6. Incomplete commenting, 7. Unused variables, 8. Empty catch block, 9. Unnecessary comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
feature envy | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Inconsistent naming, 6 Incomplete commenting, 7 Unused variables, 8 Empty catch block, 9 Unnecessary comments | t | f | t | . Long method, 3. Duplicate code, 4. Magic numbers, 5. Inconsistent naming, 6. Incomplete commenting, 7. Unused variables, 8. Empty catch block, 9. Unnecessary comments. | 0 | 10138 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 1155 | 10138 | |
| 1157 | //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) rhs=BitwiseORExpression)* public Group getGroup_1() { return cGroup_1; } // => ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1_0() { return cGroup_1_0; } public class LogicalANDExpressionElements { YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | () { return cGroup_ | t | f | f | () { return cGroup_ | data class | 0 | 10144 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 1157 | 10144 |
| 1157 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | long method, data class | t | t | t | long method | 0 | 10144 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 1157 | 10144 | |
| 1163 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10179 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 1 | 1163 | 10179 | |
| 1163 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10179 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 2 | 1163 | 10179 |
| 1165 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | long method, data class | t | t | t | long method | 0 | 10183 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 1 | 1165 | 10183 | |
| 1165 | YES, I found bad smells. the bad smells are: 1. Long method 2. Class data should be private | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | Long method2 Class data should be private | t | f | f | . Long method2. Class data should be private | data class | 0 | 10183 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 2 | 1165 | 10183 |
| 1167 | {"message": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10186 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 1 | 1167 | 10186 |
| 1167 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10186 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 2 | 1167 | 10186 |
| 1168 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
long method | 1. long method | t | t | t | 0 | 10191 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 1168 | 10191 | ||
| 1168 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
long method | Long method | t | f | t | 0 | 10191 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1168 | 10191 | ||
| 1169 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | Long method2 Magic numbers3 Feature envy | t | f | t | 0 | 10192 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1169 | 10192 | ||
| 1170 | { "message": "YES I found bad smells", "detected_bad_smells": "the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | the bad smells are: 1. long method | t | t | f | the bad smells are: 1. long method | data class | 0 | 10194 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 1 | 1170 | 10194 |
| 1170 | opens = new Open[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10194 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 2 | 1170 | 10194 |
| 1171 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10196 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 1 | 1171 | 10196 | |
| 1171 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10196 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 2 | 1171 | 10196 |
| 1172 | {"output": "YES I found bad smells\nthe bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 10197 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 1172 | 10197 | ||
| 1172 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10197 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 1172 | 10197 | |
| 1173 | { "message": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | 1. long method | t | t | t | 0 | 10199 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 1 | 1173 | 10199 | ||
| 1173 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10199 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 2 | 1173 | 10199 | ||
| 1174 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | data class | t | t | t | 0 | 10210 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 1 | 1174 | 10210 | ||
| 1174 | YES I found bad smells 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 10210 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 2 | 1174 | 10210 |
| 1179 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10227 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1179 | 10227 | |
| 1179 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10227 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1179 | 10227 | ||
| 1180 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | data class | t | t | t | 0 | 10230 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1180 | 10230 | ||
| 1180 | YES I found bad smells the bad smells are: 1. Data class, 2. Lazy class, 3. Long methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Data class, 2 Lazy class, 3 Long methods | t | f | t | 2. Lazy class, 3. Long methods | 0 | 10230 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1180 | 10230 | |
| 1181 | { "NO, I did not find any bad smell" : "the bad smells are:" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | "the bad smells are | f | f | f | "the bad smells are | data class | 0 | 10234 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 1181 | 10234 |
| 1181 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10234 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 2 | 1181 | 10234 |
| 1183 | { "output": "YES I found bad smells the bad smells are: 4. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | 4. long method | t | t | f | 4. long method | data class | 0 | 10238 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 1183 | 10238 |
| 1183 | YES, I found bad smells: 1. Feature envy 2. Duplicate code 3. Long method 4. Data class 5. Lazy class 6. Large class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | Feature envy 2 Duplicate code 3 Long method 4 Data class 5 Lazy class 6 Large class | t | f | t | 0 | 10238 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 1183 | 10238 | ||
| 1188 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | long method, data class | t | t | t | data class | 0 | 10247 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 1188 | 10247 | |
| 1188 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10247 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 1188 | 10247 | ||
| 1190 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 10253 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 1190 | 10253 | |
| 1190 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10253 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 1190 | 10253 | ||
| 1191 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 10256 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 1 | 1191 | 10256 |
| 1191 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 10256 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 2 | 1191 | 10256 |
| 1194 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
long method | long method | t | t | t | 0 | 10265 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 1 | 1194 | 10265 | ||
| 1194 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10265 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 1194 | 10265 | ||
| 1195 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10266 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 1195 | 10266 | |
| 1197 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | long method, data class | t | t | t | data class | 0 | 10271 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1197 | 10271 | |
| 1197 | YES, I found bad smells. The bad smells are: 1. Long method 2. Repeating code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Repeating code3 Feature envy | t | f | t | 0 | 10271 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1197 | 10271 | ||
| 1199 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | data class | t | t | t | 0 | 10278 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 1199 | 10278 | ||
| 1199 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 10278 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 1199 | 10278 |
| 1200 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 10279 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1200 | 10279 | |
| 1200 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication (in the if statements for different subclasses of colWidth) 4. Inconsistent formatting (spacing, use of braces) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy3 Code duplication (in the if statements for different subclasses of colWidth)4 Inconsistent formatting (spacing, use of braces) | t | f | t | use of braces) | 0 | 10279 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1200 | 10279 | |
| 1201 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | long method, data class | t | t | t | long method | 0 | 10284 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 1 | 1201 | 10284 | |
| 1201 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10284 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 2 | 1201 | 10284 |
| 1203 | { "response": "YES I found bad smells", "detected_bad_smells": [ 1.29, 2.27 ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | 1.29, 2.27 | t | t | f | 1.29, 2.27 | data class | 0 | 10286 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 1 | 1203 | 10286 |
| 1203 | Yes I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10286 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 2 | 1203 | 10286 |
| 1204 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10287 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 2 | 1204 | 10287 | |
| 1204 | {"response":"YES I found bad smells","bad smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method | t | t | t | 0 | 10287 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 1204 | 10287 | ||
| 1205 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10288 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 1205 | 10288 |
| 1207 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | data class, long method | t | t | t | data class | 0 | 10290 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 1207 | 10290 | |
| 1207 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10290 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 1207 | 10290 | ||
| 1209 | YES I found bad smells the bad smells are: 1. Too many comments - the code has a lot of comments that could potentially be refactored into more readable, self-explanatory code. 2. Long constructor - the class contains a long constructor which can be refactored into smaller methods. 3. Feature envy - the class has a lot of getters and setters for properties that belong to the QuickfixjEngine class, indicating that there might be a better design where these properties are directly accessed in the QuickfixjEngine class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | Too many comments - the code has a lot of comments that could potentially be refactored into more readable, self-explanatory code2 Long constructor - the class contains a long constructor which can be refactored into smaller methods3 Feature envy - the class has a lot of getters and setters for properties that belong to the QuickfixjEngine class, indicating that there might be a better design where these properties are directly accessed in the QuickfixjEngine class | t | f | f | . Too many comments - the code has a lot of comments that could potentially be refactored into more readable, self-explanatory code.2. Long constructor - the class contains a long constructor which can be refactored into smaller methods.3. Feature envy - the class has a lot of getters and setters for properties that belong to the QuickfixjEngine class, indicating that there might be a better design where these properties are directly accessed in the QuickfixjEngine class. | data class | 0 | 10306 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 2 | 1209 | 10306 |
| 1211 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10310 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 1211 | 10310 | |
| 1211 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10310 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 1211 | 10310 | ||
| 1212 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | data class, long method | t | t | t | long method | 0 | 10312 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 1 | 1212 | 10312 | |
| 1212 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Violation of Single Responsibility Principle (SRP) 6. Overuse of modifiers (e.g. final, volatile) 7. Inadequate exception handling (e.g. thrown but not caught) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | Long method2 Feature envy3 Duplicate code4 Inconsistent naming conventions5 Violation of Single Responsibility Principle (SRP) 6 Overuse of modifiers (eg final, volatile) 7 Inadequate exception handling (eg thrown but not caught) | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent naming conventions5. Violation of Single Responsibility Principle (SRP) 6. Overuse of modifiers (e.g. final, volatile) 7. Inadequate exception handling (e.g. thrown but not caught) | data class | 0 | 10312 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 2 | 1212 | 10312 |
| 1214 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10314 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1214 | 10314 |
| 1214 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Switch statement | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | Long method2 Feature envy3 Duplicate code4 Switch statement | t | f | t | 0 | 10314 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1214 | 10314 | ||
| 1215 | } YES I found bad smells the bad smells are: 1. Debug code - commented out code and print statements that are not needed for production. 2. Inconsistent formatting. 3. Unused code - methods clearEOF() and setEOF() are never called. 4. Lack of clarity - variable names like f, fp, and eof are not descriptive. 5. Magic numbers - values such as -1 and 0 are used without explanation. 6. Long method - the method is over 20 lines long, which can make it difficult to understand and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | Debug code - commented out code and print statements that are not needed for production2 Inconsistent formatting3 Unused code - methods clearEOF() and setEOF() are never called4 Lack of clarity - variable names like f, fp, and eof are not descriptive5 Magic numbers - values such as - | t | f | f | . Debug code - commented out code and print statements that are not needed for production.2. Inconsistent formatting.3. Unused code - methods clearEOF() and setEOF() are never called.4. Lack of clarity - variable names like f, fp, and eof are not descriptive.5. Magic numbers - values such as - | long method | 0 | 10318 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 1215 | 10318 |
| 1217 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method | t | t | t | 0 | 10323 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1217 | 10323 | ||
| 1217 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent formatting 5. Poor naming conventions (e.g. "sql", "sel", "params") 6. Possible code duplication (e.g. in the "if (updateParams == null)" and "else" blocks) 7. Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()") 8. Possible excessive use of boolean flags (e.g. "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause") 9. Possible violation of SOLID principles (e.g. Single Responsibility, Open/Closed) 10. Lack of comments and documentation on the purpose and logic of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Long method2 Feature envy3 Duplicate code4 Inconsistent formatting5 Poor naming conventions (eg "sql", "sel", "params")6 Possible code duplication (eg in the "if (updateParams == null)" and "else" blocks)7 Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()")8 Possible excessive use of boolean flags (eg "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause")9 Possible violation of SOLID principles (eg Single Responsibility, Open/Closed) | t | f | t | "sel", "params")6. Possible code duplication (e.g. in the "if (updateParams == null)" and "else" blocks)7. Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()")8. Possible excessive use of boolean flags (e.g. "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause")9. Possible violation of SOLID principles (e.g. Single Responsibility, Open/Closed) | 0 | 10323 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1217 | 10323 | |
| 1218 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10324 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1218 | 10324 |
| 1218 | YES I found bad smells the bad smells are: 1. Long method, 2. Complex conditionals, 3. Duplicate code, 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | Long method, 2 Complex conditionals, 3 Duplicate code, 4 Feature envy | t | f | t | . Long method, 2. Complex conditionals, 3. Duplicate code | 0 | 10324 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1218 | 10324 | |
| 1221 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10334 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 1221 | 10334 | |
| 1221 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Inappropriate naming, 4. Long parameter list, 5. Indecent exposure/Inappropriate intimacy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | Long method, 2 Feature envy, 3 Inappropriate naming, 4 Long parameter list, 5 Indecent exposure/Inappropriate intimacy | t | f | f | . Long method, 2. Feature envy, 3. Inappropriate naming, 4. Long parameter list, 5. Indecent exposure/Inappropriate intimacy. | data class | 0 | 10334 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 1221 | 10334 |
| 1222 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10338 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 1222 | 10338 |
| 1222 | YES I found bad smells the bad smells are: Long method, Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 10338 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 1222 | 10338 | |
| 1223 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | 1: data class | t | t | t | 0 | 10340 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 1 | 1223 | 10340 | ||
| 1223 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy 3. Lack of encapsulation/ data hiding | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | Long methods2 Feature envy3 Lack of encapsulation/ data hiding | t | f | f | . Long methods2. Feature envy3. Lack of encapsulation/ data hiding | data class | 0 | 10340 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 2 | 1223 | 10340 |
| 1224 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 10343 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 1224 | 10343 | ||
| 1224 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10343 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 1224 | 10343 | ||
| 1225 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | 1: long method | t | t | t | 0 | 10351 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 1225 | 10351 | ||
| 1225 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10351 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 1225 | 10351 | |
| 1226 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10352 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 1226 | 10352 |
| 1226 | YES I found bad smells The bad smells are: 1. Duplicate code (calling findNuageVspCmsIdForDeviceOrHost() twice) 2. Long method 3. Feature envy (method is using data from NuageVspDeviceVO instead of its own data) 4. Use of null instead of proper error handling 5. Possible use of magic numbers (SyncType.REGISTER is compared multiple times) 6. Complex conditional logic (multiple if/else statements) 7. Unnecessary parameter passing (nuageVspDevice.getHostId() is passed to multiple methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | Duplicate code (calling findNuageVspCmsIdForDeviceOrHost() twice)2 Long method3 Feature envy (method is using data from NuageVspDeviceVO instead of its own data)4 Use of null instead of proper error handling5 Possible use of magic numbers (SyncTypeREGISTER is compared multiple times)6 Complex conditional logic (multiple if/else statements)7 Unnecessary parameter passing (nuageVspDevicegetHostId() is passed to multiple methods) | t | f | t | 0 | 10352 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 1226 | 10352 | ||
| 1227 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method | t | t | t | 0 | 10353 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1227 | 10353 | ||
| 1227 | YES I found bad smells the bad smells are: 1. Commented out code 2. Long method 3. Feature envy 4. Inconsistent indentation 5. Non-descriptive variable names 6. Nested if statements 7. Lack of error handling for exceptions 8. Multiple responsibilities in one method (parsing, handling exceptions, building results map) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Commented out code2 Long method3 Feature envy4 Inconsistent indentation5 Non-descriptive variable names6 Nested if statements7 Lack of error handling for exceptions8 Multiple responsibilities in one method (parsing, handling exceptions, building results map) | t | f | t | handling exceptions, building results map) | 0 | 10353 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1227 | 10353 | |
| 1228 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10354 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1228 | 10354 |
| 1228 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10354 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1228 | 10354 | ||
| 1229 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10360 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 1 | 1229 | 10360 | |
| 1229 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 10360 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 2 | 1229 | 10360 |
| 1230 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | 1. data class | t | t | t | 0 | 10362 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 1230 | 10362 | ||
| 1230 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long methods 3. Getter and setter methods instead of using constructor injection or builder pattern. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Feature envy2 Long methods3 Getter and setter methods instead of using constructor injection or builder pattern | t | f | f | . Feature envy2. Long methods3. Getter and setter methods instead of using constructor injection or builder pattern. | data class | 0 | 10362 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 1230 | 10362 |
| 1231 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | data class | t | t | t | 0 | 10364 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 1231 | 10364 | ||
| 1231 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10364 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 1231 | 10364 |
| 1234 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10369 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 1234 | 10369 |
| 1234 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10369 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 1234 | 10369 | ||
| 1238 | { "response": "YES I found bad smells", "detected_smells": [ "the bad smells are:", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | the bad smells are:, 2. feature envy | t | t | t | the bad smells are: | 0 | 10397 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 1238 | 10397 | |
| 1238 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method 3. Duplicate code 4. Magic numbers 5. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | Feature envy2 Long method3 Duplicate code4 Magic numbers5 Inconsistent naming conventions | t | f | t | 0 | 10397 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1238 | 10397 | ||
| 1239 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10404 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 1239 | 10404 | ||
| 1241 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10410 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 1241 | 10410 |
| 1241 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10410 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 1241 | 10410 | ||
| 1242 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10414 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 2 | 1242 | 10414 |
| 1244 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | long method | t | t | f | long method | data class | 0 | 10416 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 1 | 1244 | 10416 |
| 1244 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Comments as code 5. Magic numbers 6. Inconsistent naming conventions 7. Complex nested conditions 8. Use of static variables and methods 9. Poor exception handling 10. Use of getters and setters in the MetricsImpl class 11. Poor encapsulation 12. Violation of single responsibility principle | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | Long method2 Feature envy3 Duplicate code4 Comments as code5 Magic numbers6 Inconsistent naming conventions7 Complex nested conditions8 Use of static variables and methods9 Poor exception handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Comments as code5. Magic numbers6. Inconsistent naming conventions7. Complex nested conditions8. Use of static variables and methods9. Poor exception handling | data class | 0 | 10416 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 2 | 1244 | 10416 |
| 1245 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10419 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 1245 | 10419 |
| 1246 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | long method, data class | t | t | t | data class | 0 | 10421 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1246 | 10421 | |
| 1246 | YES I found bad smells. the bad smells are: 1.Long method 3.Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method3Magic numbers | t | f | t | 0 | 10421 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1246 | 10421 | ||
| 1249 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | data class | t | t | t | 0 | 10434 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 1249 | 10434 | ||
| 1249 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | Feature envy | t | f | f | .Feature envy | data class | 0 | 10434 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 1249 | 10434 |
| 1250 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10436 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1250 | 10436 |
| 1252 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | data class, long method | t | t | t | long method | 0 | 10442 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 1252 | 10442 | |
| 1252 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10442 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 1252 | 10442 |
| 1253 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | f | f | f | data class | 0 | 10456 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 1253 | 10456 | ||
| 1254 | {"message": "YES, I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 10475 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 1254 | 10475 | |
| 1254 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10475 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 1254 | 10475 |
| 1257 | YES I found bad smells the bad smells are: 1. Long class, 2. Data class, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Long class, 2 Data class, 3 Feature envy | t | f | t | . Long class, 3. Feature envy | 0 | 10498 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1257 | 10498 | |
| 1262 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | long method | t | t | t | 0 | 10513 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 1262 | 10513 | ||
| 1262 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10513 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 1262 | 10513 | ||
| 1263 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | data class | t | t | t | 0 | 10524 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 1 | 1263 | 10524 | ||
| 1263 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 10524 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 2 | 1263 | 10524 |
| 1265 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | data class, long method | t | t | t | long method | 0 | 10541 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 1 | 1265 | 10541 | |
| 1265 | YES I found bad smells 1. Long method 2. Feature envy 3. Code duplication (duplicate code in constructors) 4. Lack of encapsulation (direct access to class variables) 5. Violation of Single Responsibility Principle (class has multiple responsibilities - representing a DrillRelNode and a TableScan) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | Long method2 Feature envy3 Code duplication (duplicate code in constructors)4 Lack of encapsulation (direct access to class variables)5 Violation of Single Responsibility Principle (class has multiple responsibilities - representing a DrillRelNode and a TableScan) | t | f | f | . Long method2. Feature envy3. Code duplication (duplicate code in constructors)4. Lack of encapsulation (direct access to class variables)5. Violation of Single Responsibility Principle (class has multiple responsibilities - representing a DrillRelNode and a TableScan) | data class | 0 | 10541 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 2 | 1265 | 10541 |
| 1269 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | long method | t | t | t | 0 | 10565 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1269 | 10565 | ||
| 1269 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10565 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1269 | 10565 | ||
| 1270 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10566 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1270 | 10566 |
| 1270 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10566 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1270 | 10566 | ||
| 1272 | {"result": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10573 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1272 | 10573 | |
| 1272 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10573 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1272 | 10573 | ||
| 1277 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10590 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 1 | 1277 | 10590 |
| 1277 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10590 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 2 | 1277 | 10590 | ||
| 1278 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 10592 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1278 | 10592 | ||
| 1278 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Multiple if statements in a row 4. Hardcoded values for class types, which could lead to maintenance issues if types change in the future 5. Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method2 Feature envy3 Multiple if statements in a row4 Hardcoded values for class types, which could lead to maintenance issues if types change in the future5 Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | t | f | t | which could lead to maintenance issues if types change in the future5. Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | 0 | 10592 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1278 | 10592 | |
| 1279 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10593 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1279 | 10593 | ||
| 1279 | The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Feature envy | f | f | t | 0 | 10593 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1279 | 10593 | ||
| 1282 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10603 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 1282 | 10603 | |
| 1282 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10603 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 1282 | 10603 | ||
| 1284 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10606 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 1284 | 10606 |
| 1284 | YES I found bad smells the bad smells are: 1. Conditional complexity 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | Conditional complexity 2 Long method | t | f | f | . Conditional complexity 2. Long method | feature envy | 0 | 10606 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 1284 | 10606 |
| 1285 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10608 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 1285 | 10608 |
| 1286 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10611 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 1286 | 10611 |
| 1287 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | 1. long method | t | t | t | 0 | 10613 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1287 | 10613 | ||
| 1287 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10613 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1287 | 10613 | ||
| 1288 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10614 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1288 | 10614 |
| 1288 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10614 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1288 | 10614 | ||
| 1289 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | long method | t | t | f | long method | data class | 0 | 10615 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 1289 | 10615 |
| 1289 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 10615 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 1289 | 10615 |
| 1291 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 10618 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 1 | 1291 | 10618 | ||
| 1291 | YES I found bad smells: 1. Getter and setter methods present for a single private field (code repetition). 2. Inconsistent use of annotations for the 'name' field. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Getter and setter methods present for a single private field (code repetition) 2 Inconsistent use of annotations for the 'name' field | t | f | f | . Getter and setter methods present for a single private field (code repetition). 2. Inconsistent use of annotations for the 'name' field. | data class | 0 | 10618 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 2 | 1291 | 10618 |
| 1292 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10621 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 2 | 1292 | 10621 |
| 1293 | {"message":"YES I found bad smells","bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method, data class | t | t | t | data class | 0 | 10623 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1293 | 10623 | |
| 1293 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10623 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1293 | 10623 | ||
| 1294 | { "message": "YES I found bad smells the bad smells are:", "bad smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 10624 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1294 | 10624 |
| 1294 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10624 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1294 | 10624 | ||
| 1297 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | data class | t | t | t | 0 | 10637 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 1 | 1297 | 10637 | ||
| 1297 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10637 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 2 | 1297 | 10637 |
| 1298 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Complex code, 4.Duplicated code, 5.Exception handling within a loop, 6.Use of abbreviations in method name, 7.Consider splitting up the method into smaller methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | Long method, 2Magic numbers, 3Complex code, 4Duplicated code, 5Exception handling within a loop, 6Use of abbreviations in method name, 7Consider splitting up the method into smaller methods | t | f | t | 2.Magic numbers, 3.Complex code, 4.Duplicated code, 5.Exception handling within a loop, 6.Use of abbreviations in method name, 7.Consider splitting up the method into smaller methods. | 0 | 10639 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 1298 | 10639 | |
| 1299 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10640 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 1 | 1299 | 10640 |
| 1299 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10640 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 1299 | 10640 | |
| 1301 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | data class | t | t | t | 0 | 10658 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 1 | 1301 | 10658 | ||
| 1301 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Data class, 4. Data clumps, 5. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | Long method, 2 Feature envy, 3 Data class, 4 Data clumps, 5 Primitive obsession | t | f | t | . Long method, 2. Feature envy, 4. Data clumps, 5. Primitive obsession | 0 | 10658 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 2 | 1301 | 10658 | |
| 1304 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 10672 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 1 | 1304 | 10672 | |
| 1304 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10672 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 2 | 1304 | 10672 |
| 1305 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10673 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 1305 | 10673 | |
| 1305 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10673 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 1305 | 10673 | |
| 1308 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10677 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 1 | 1308 | 10677 |
| 1308 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10677 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 2 | 1308 | 10677 |
| 1309 | YES I found bad smells the bad smells are: 1. Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes, indicating a potential feature envy smell. 2. Long method: The method "toBulkOperation" is quite long and contains multiple branches and nested logic, indicating a potential long method smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes, indicating a potential feature envy smell2 Long method: The method "toBulkOperation" is quite long and contains multiple branches and nested logic, indicating a potential long method smell | t | f | t | . Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes | 0 | 10679 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1309 | 10679 | |
| 1309 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10679 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1309 | 10679 | |
| 1310 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | f | f | f | feature envy | 0 | 10680 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1310 | 10680 | ||
| 1310 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10680 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1310 | 10680 |
| 1311 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method, data class | t | t | t | data class | 0 | 10681 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 1311 | 10681 | |
| 1311 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10681 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 1311 | 10681 | ||
| 1313 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10683 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 1 | 1313 | 10683 | |
| 1313 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10683 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 2 | 1313 | 10683 | ||
| 1314 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | long method | t | t | t | 0 | 10686 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1314 | 10686 | ||
| 1314 | YES I found bad smells the bad smells are: 1. Long method 2. Loss of cohesion | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Loss of cohesion | t | f | t | 0 | 10686 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1314 | 10686 | ||
| 1315 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | 1: data class | t | t | t | 0 | 10688 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 1 | 1315 | 10688 | ||
| 1315 | YES, I found bad smells the bad smells are: 1. Long method 2. Repetitive code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | Long method2 Repetitive code | t | f | f | . Long method2. Repetitive code | data class | 0 | 10688 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 2 | 1315 | 10688 |
| 1317 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10691 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1317 | 10691 | |
| 1317 | YES I found bad smells the bad smells are: 1. Commented out code 2. Complex conditional statements 3. Violation of Single Responsibility Principle (SRP) - the method is responsible for both parsing and adding to a projection 4. Magic numbers 5. Inconsistent formatting and spacing 6. Inefficient use of whitespace 7. Potential Null Pointer Exception 8. Confusing variable names (e.g. nameSeg, arraySeg) 9. Duplicate code in the if-else statement 10. Non-descriptive and vague method name 11. Nested conditional statements 12. Potential error-prone code (e.g. using a logger to throw an exception) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Commented out code 2 Complex conditional statements 3 Violation of Single Responsibility Principle (SRP) - the method is responsible for both parsing and adding to a projection 4 Magic numbers 5 Inconsistent formatting and spacing 6 Inefficient use of whitespace 7 Potential Null Pointer Exception 8 Confusing variable names (eg nameSeg, arraySeg) 9 Duplicate code in the if-else statement | t | f | f | . Commented out code 2. Complex conditional statements 3. Violation of Single Responsibility Principle (SRP) - the method is responsible for both parsing and adding to a projection 4. Magic numbers 5. Inconsistent formatting and spacing 6. Inefficient use of whitespace 7. Potential Null Pointer Exception 8. Confusing variable names (e.g. nameSeg, arraySeg) 9. Duplicate code in the if-else statement | long method | 0 | 10691 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1317 | 10691 |
| 1318 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 10692 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1318 | 10692 |
| 1318 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10692 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1318 | 10692 | ||
| 1321 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10698 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 1321 | 10698 |
| 1321 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10698 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 1321 | 10698 | ||
| 1322 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | long method | t | t | t | 0 | 10699 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 1322 | 10699 | ||
| 1322 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10699 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 1322 | 10699 | ||
| 1325 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10702 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1325 | 10702 | |
| 1325 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10702 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1325 | 10702 | ||
| 1327 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | long method | t | t | f | long method | data class | 0 | 10704 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 1 | 1327 | 10704 |
| 1327 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10704 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 2 | 1327 | 10704 |
| 1328 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | data class | t | t | t | 0 | 10705 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 1 | 1328 | 10705 | ||
| 1328 | YES I found bad smells The bad smells are: 1. Commented-out code 2. Inconsistent formatting 3. Long parameter list 4. Unnecessary constructors 5. Unnecessary use of "this" keyword 6. Inconsistent variable naming (e.g. "mainDexListCount" and "dexCount") 7. Magic numbers (e.g. "0" and "2" in @Config) 8. No clear purpose or functionality stated in class or methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | Commented-out code2 Inconsistent formatting3 Long parameter list4 Unnecessary constructors5 Unnecessary use of "this" keyword6 Inconsistent variable naming (eg "mainDexListCount" and "dexCount")7 Magic numbers (eg "0" and "2" in @Config)8 No clear purpose or functionality stated in class or methods | t | f | f | . Commented-out code2. Inconsistent formatting3. Long parameter list4. Unnecessary constructors5. Unnecessary use of "this" keyword6. Inconsistent variable naming (e.g. "mainDexListCount" and "dexCount")7. Magic numbers (e.g. "0" and "2" in @Config)8. No clear purpose or functionality stated in class or methods. | data class | 0 | 10705 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 1328 | 10705 |
| 1329 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | long method | t | t | f | long method | data class | 0 | 10707 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 1329 | 10707 |
| 1329 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10707 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 1329 | 10707 |
| 1330 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10710 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 1 | 1330 | 10710 |
| 1330 | YES I found bad smells. 1. Feature envy, 2. Magic numbers, 3. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | Feature envy, 2 Magic numbers, 3 Long method | t | f | f | . Feature envy, 2. Magic numbers, 3. Long method | data class | 0 | 10710 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 2 | 1330 | 10710 |
| 1332 | {"response": "YES I found bad smells. the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | 1. data class | t | t | t | 0 | 10716 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 1332 | 10716 | ||
| 1332 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10716 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 1332 | 10716 |
| 1335 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | data class | t | t | t | 0 | 10724 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 1 | 1335 | 10724 | ||
| 1335 | YES I found bad smells the bad smells are: 1. Duplicate Code (same default constructor defined in class and commented out) 2. Inconsistent Formatting (commented out constructor is indented with 4 spaces instead of 2) 3. Inconsistent Naming (package_name and package_id variables not following standard camelCase naming convention) 4. Magic Number (package_id is assigned 0 without any explanation) 5. Feature Envy (package_id is being modified and used within the class, despite it being a parameter for the constructor) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | Duplicate Code (same default constructor defined in class and commented out)2 Inconsistent Formatting (commented out constructor is indented with 4 spaces instead of 2)3 Inconsistent Naming (package_name and package_id variables not following standard camelCase naming convention)4 Magic Number (package_id is assigned 0 without any explanation)5 Feature Envy (package_id is being modified and used within the class, despite it being a parameter for the constructor) | t | f | f | . Duplicate Code (same default constructor defined in class and commented out)2. Inconsistent Formatting (commented out constructor is indented with 4 spaces instead of 2)3. Inconsistent Naming (package_name and package_id variables not following standard camelCase naming convention)4. Magic Number (package_id is assigned 0 without any explanation)5. Feature Envy (package_id is being modified and used within the class, despite it being a parameter for the constructor) | data class | 0 | 10724 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 2 | 1335 | 10724 |
| 1338 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | long method | t | t | t | 0 | 10733 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 1 | 1338 | 10733 | ||
| 1338 | YES I found bad smells The bad smells are: 1. Magic numbers 2. Long method 3. Complex logic 4. Feature envy 5. Poor variable naming 6. Repeated code 7. Inconsistent formatting 8. Inefficient use of memory 9. Use of ternary operator 10. Poor exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | Magic numbers2 Long method3 Complex logic4 Feature envy5 Poor variable naming6 Repeated code7 Inconsistent formatting8 Inefficient use of memory9 Use of ternary operator | t | f | t | 0 | 10733 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 2 | 1338 | 10733 | ||
| 1341 | {"output": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | 1. data class | t | t | t | 0 | 10742 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 1 | 1341 | 10742 | ||
| 1341 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 10742 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 2 | 1341 | 10742 |
| 1342 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10744 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 1 | 1342 | 10744 |
| 1342 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10744 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 2 | 1342 | 10744 | ||
| 1343 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10745 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1343 | 10745 | ||
| 1344 | { "error": "Please check the list of common code smells in the input and specify what bad smells are listed." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Not specified | f | f | f | false | 0 | 10746 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1344 | 10746 | |
| 1344 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10746 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1344 | 10746 | |
| 1345 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10747 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 1345 | 10747 | |
| 1345 | YES, I found bad smells the bad smells are: 1.Long method, 2.Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind. This code is tightly coupled. 3.Magic numbers: Type IDs like testIT.getTypeID() make the code less readable. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method, 2Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind This code is tightly coupled 3Magic numbers: Type IDs like testITgetTypeID() make the code less readable | t | f | t | 2.Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind. This code is tightly coupled. 3.Magic numbers: Type IDs like testIT.getTypeID() make the code less readable. | 0 | 10747 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 1345 | 10747 | |
| 1348 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | long method | t | t | t | 0 | 10753 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 1348 | 10753 | ||
| 1348 | YES, I found bad smells. the bad smells are: 1.Inappropriate naming, 2. Long method, 3. Feature envy, 4. Nested conditionals, 5. Mixed levels of abstraction, 6. Repeated code, 7. Data clumps, 8. Primitive obsession. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | Inappropriate naming, 2 Long method, 3 Feature envy, 4 Nested conditionals, 5 Mixed levels of abstraction, 6 Repeated code, 7 Data clumps, 8 Primitive obsession | t | f | t | .Inappropriate naming, 3. Feature envy, 4. Nested conditionals, 5. Mixed levels of abstraction, 6. Repeated code, 7. Data clumps, 8. Primitive obsession. | 0 | 10753 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 1348 | 10753 | |
| 1349 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10754 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 1349 | 10754 |
| 1349 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10754 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 1349 | 10754 | ||
| 1351 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10757 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 1 | 1351 | 10757 |
| 1351 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10757 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 2 | 1351 | 10757 | ||
| 1352 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | long method | t | t | t | 0 | 10761 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1352 | 10761 | ||
| 1352 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10761 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1352 | 10761 | ||
| 1354 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | data class | t | t | t | 0 | 10763 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 1 | 1354 | 10763 | ||
| 1354 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10763 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 2 | 1354 | 10763 |
| 1359 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10776 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1359 | 10776 |
| 1359 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Switch statement 4. State variable usage 5. Feature envy (using input stream methods instead of TokenStream methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | Long method2 Duplicate code3 Switch statement4 State variable usage5 Feature envy (using input stream methods instead of TokenStream methods) | t | f | t | 0 | 10776 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1359 | 10776 | ||
| 1361 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10778 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 1361 | 10778 |
| 1361 | YES I found bad smells The bad smells are:1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10778 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 1361 | 10778 | |
| 1362 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10779 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1362 | 10779 |
| 1362 | YES I found bad smells, the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10779 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1362 | 10779 | |
| 1363 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10780 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1363 | 10780 | |
| 1363 | YES I found bad smells the bad smells are: 1.Long method 2.Magic numbers 3.Duplicate code 4.Commented code 5.Inconsistent formatting 6.Lack of proper variable naming 7.Complex conditional statements 8.Multiple responsibilities within one method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long method2Magic numbers3Duplicate code4Commented code5Inconsistent formatting6Lack of proper variable naming7Complex conditional statements8Multiple responsibilities within one method | t | f | t | 0 | 10780 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1363 | 10780 | ||
| 1366 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | long method | t | t | f | long method | data class | 0 | 10787 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 1366 | 10787 |
| 1366 | the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method | f | f | f | . Long method | data class | 0 | 10787 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 1366 | 10787 |
| 1368 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10790 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 2 | 1368 | 10790 |
| 1369 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | long method, data class | t | t | t | long method | 0 | 10791 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 1 | 1369 | 10791 | |
| 1369 | YES I found bad smells the bad smells are: 1) Long method, 2) Feature envy, 3) Duplicate code, 4) Poor naming conventions, 5) Use of raw types rather than generic types, 6) Inappropriate abstraction, 7) Use of static state on classes, 8) Use of nested classes for every event emitter. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | ) Long method, 2) Feature envy,3) Duplicate code, 4) Poor naming conventions, 5) Use of raw types rather than generic types, 6) Inappropriate abstraction, 7) Use of static state on classes, 8) Use of nested classes for every event emitter | t | f | f | ) Long method, 2) Feature envy, 3) Duplicate code, 4) Poor naming conventions, 5) Use of raw types rather than generic types, 6) Inappropriate abstraction, 7) Use of static state on classes, 8) Use of nested classes for every event emitter. | data class | 0 | 10791 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 2 | 1369 | 10791 |
| 1371 | {"response": "YES I found bad smells", "bad_smells": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | 2. data class | t | t | t | 0 | 10800 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 1 | 1371 | 10800 | ||
| 1371 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 10800 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 2 | 1371 | 10800 |
| 1373 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method, data class | t | t | t | data class | 0 | 10803 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 1373 | 10803 | |
| 1373 | YES I found bad smells, The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10803 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 1373 | 10803 | ||
| 1374 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10804 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 1374 | 10804 |
| 1374 | YES, I found bad smellsThe bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10804 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 1374 | 10804 | ||
| 1376 | { "response": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | 1. data class | t | t | t | 0 | 10810 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 1 | 1376 | 10810 | ||
| 1376 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 10810 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 2 | 1376 | 10810 |
| 1377 | { "error": "The provided Java code is too lengthy for me to analyze. Please provide a shorter code snippet for analysis." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Not specified | f | f | f | false | 0 | 10811 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1377 | 10811 | |
| 1377 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10811 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1377 | 10811 |
| 1378 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10816 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 1 | 1378 | 10816 |
| 1378 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10816 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 2 | 1378 | 10816 |
| 1379 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | long method | t | t | t | 0 | 10817 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 1 | 1379 | 10817 | ||
| 1379 | YES, I found bad smells - long method, feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | t | f | f | long method | 0 | 10817 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 2 | 1379 | 10817 | ||
| 1386 | { "message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10834 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 1386 | 10834 | |
| 1386 | YES I found bad smells the bad smells are: 1) Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | )Long method | t | f | f | )Long method | data class | 0 | 10834 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 1386 | 10834 |
| 1387 | { "output": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | 1. data class | t | t | t | 0 | 10837 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 1 | 1387 | 10837 | ||
| 1387 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10837 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 1387 | 10837 |
| 1388 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method, data class | t | t | t | data class | 0 | 10839 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1388 | 10839 | |
| 1388 | Yes I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Nested conditionals, 6. Large number of parameters, 7. Lack of comments/documentation, 8. High complexity/low readability, 9. Inconsistent formatting, 10. Hard-coded values/strings, 11. Use of deprecated methods, 12. Lack of abstraction/separation of concerns, 13. Potential NullPointerExceptions, 14. Unused variables, 15. Lack of error handling/reporting, 16. Inadequate naming of variables/methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Nested conditionals, 6 Large number of parameters, 7 Lack of comments/documentation, 8 High complexity/low readability, 9 Inconsistent formatting, | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Nested conditionals, 6. Large number of parameters, 7. Lack of comments/documentation, 8. High complexity/low readability, 9. Inconsistent formatting, | 0 | 10839 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1388 | 10839 | |
| 1389 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | 'Long Method' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',o,n,g," ",M,t,h,o,d,'} | 0 | 10840 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1389 | 10840 |
| 1389 | YES I found bad smells the bad smells are: 1.Feature envy,2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | Feature envy,2Long method | t | f | t | 2.Long method | 0 | 10840 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1389 | 10840 | |
| 1390 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 10841 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 1 | 1390 | 10841 | |
| 1390 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 10841 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 2 | 1390 | 10841 | |
| 1393 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10847 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 1 | 1393 | 10847 |
| 1393 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 10847 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 2 | 1393 | 10847 |
| 1394 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | long method | t | t | t | 0 | 10850 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1394 | 10850 | ||
| 1394 | YES I found bad smells. The detected bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10850 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1394 | 10850 | ||
| 1395 | { "message": "YES I found bad smells", "smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10851 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1395 | 10851 |
| 1395 | YES I found bad smells the bad smells are: - Feature envy - Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | - Feature envy- Long method | t | f | t | 0 | 10851 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1395 | 10851 | ||
| 1397 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 10854 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1397 | 10854 | |
| 1397 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10854 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1397 | 10854 | ||
| 1398 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long Method | t | f | f | Long Method | feature envy | 0 | 10855 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1398 | 10855 |
| 1398 | YES I found bad smells. The bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 10855 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1398 | 10855 | |
| 1399 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10858 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 1399 | 10858 |
| 1399 | YES, I found bad smells. 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10858 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 1399 | 10858 | ||
| 1400 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | long method | t | t | t | 0 | 10859 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 1400 | 10859 | ||
| 1400 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | Long method, 2 Duplicate code | t | f | t | 2. Duplicate code. | 0 | 10859 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 1400 | 10859 | |
| 1403 | { "output": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | f | f | f | data class | 0 | 10864 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 1 | 1403 | 10864 | ||
| 1403 | YES I found bad smells the bad smells are: 1. Inconsistent formatting and indentation. 2. Use of SuppressWarnings annotation, indicating a potential problem that is being ignored. 3. Use of a raw type in the Map declaration. 4. Unnecessary interface declaration within an interface. 5. Confusing and lengthy naming conventions, with multiple references to the same variables or properties. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | Inconsistent formatting and indentation2 Use of SuppressWarnings annotation, indicating a potential problem that is being ignored3 Use of a raw type in the Map declaration4 Unnecessary interface declaration within an interface5 Confusing and lengthy naming conventions, with multiple references to the same variables or properties | t | f | f | . Inconsistent formatting and indentation.2. Use of SuppressWarnings annotation, indicating a potential problem that is being ignored.3. Use of a raw type in the Map declaration.4. Unnecessary interface declaration within an interface.5. Confusing and lengthy naming conventions, with multiple references to the same variables or properties. | data class | 0 | 10864 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 2 | 1403 | 10864 |
| 1404 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10872 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 1404 | 10872 |
| 1405 | YES I found bad smells. the bad smells are: 1. No constructor provided for the Release class. 2. The Release class only consists of getter methods and lacks any business logic, which could indicate a lack of cohesion. 3. The fields in the Release class are all final, which could potentially limit flexibility and make it difficult to modify or extend the class in the future. 4. The use of @Value annotation, which may indicate an overuse of Lombok and potentially hide the underlying code implementation. 5. The lack of documentation or comments for the Release class, which could make it difficult for other developers to understand its purpose and usage. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value public class Release { private final String id; private final ProjectKey projectKey; private final String name; private final String description; private final LocalDate date; } |
data class | No constructor provided for the Release class2 The Release class only consists of getter methods and lacks any business logic, which could indicate a lack of cohesion3 The fields in the Release class are all final, which could potentially limit flexibility and make it difficult to modify or extend the class in the future4 The use of @Value annotation, which may indicate an overuse of Lombok and potentially hide the underlying code implementation5 The lack of documentation or comments for the Release class, which could make it difficult for other developers to understand its purpose and usage | t | f | f | . No constructor provided for the Release class.2. The Release class only consists of getter methods and lacks any business logic, which could indicate a lack of cohesion.3. The fields in the Release class are all final, which could potentially limit flexibility and make it difficult to modify or extend the class in the future.4. The use of @Value annotation, which may indicate an overuse of Lombok and potentially hide the underlying code implementation.5. The lack of documentation or comments for the Release class, which could make it difficult for other developers to understand its purpose and usage. | data class | 0 | 10874 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/model/Release.java/#L25-L33 | 2 | 1405 | 10874 |
| 1406 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | data class, long method | t | t | t | long method | 0 | 10877 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 1 | 1406 | 10877 | |
| 1406 | YES I found bad smells the bad smells are: 1. Long class, 2. Feature envy: the SparkVersion class has a very long list of methods and fields, making it difficult to navigate and understand. 3. Duplicate code: the versions of Spark (e.g. SPARK_1_6_0, SPARK_2_0_0) are repeated multiple times in the code, leading to potential errors if they are not all updated consistently. 4. Inconsistent naming: some methods and fields use camelCase while others use snake_case, making the code inconsistent and harder to read. 5. Magic numbers: the version is calculated using a hardcoded number format, making it unclear what the number actually represents and making the code less maintainable. 6. Poor exception handling: the code uses a generic "catch-all" exception, which can hide potential errors and make debugging difficult. 7. Feature envy: some methods (e.g. toString(), isSpark2()) rely heavily on the state of the SparkVersion class, rather than on their own state. 8. Lack of encapsulation: the fields of the class (e.g. versionString, majorVersion) are declared as public, allowing them to be accessed and modified from outside the class. This breaks the principle of encapsulation and can lead to potential errors. 9. Mixing of concerns: the class handles both Spark versioning and logic related to detecting unsupported versions and supporting secret sockets. This can make the code more complex and harder to maintain. 10. Potential data inconsistency: because the class does not enforce any rules about how the versionNumber field should be updated when modifying the major, minor, or patch versions, it could lead to data inconsistency and potential bugs. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | Long class, 2 Feature envy: the SparkVersion class has a very long list of methods and fields, making it difficult to navigate and understand3 Duplicate code: the versions of Spark (eg SPARK_ | t | f | f | . Long class, 2. Feature envy: the SparkVersion class has a very long list of methods and fields, making it difficult to navigate and understand.3. Duplicate code: the versions of Spark (e.g. SPARK_ | data class | 0 | 10877 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 2 | 1406 | 10877 |
| 1409 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | data class | t | t | t | 0 | 10897 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 1 | 1409 | 10897 | ||
| 1409 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Long parameter list 5. Shotgun surgery 6. Inappropriate intimacy 7. Unused code 8. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | Long method2 Feature envy3 Duplicate code 4 Long parameter list 5 Shotgun surgery 6 Inappropriate intimacy 7 Unused code 8 Lazy class | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Long parameter list 5. Shotgun surgery 6. Inappropriate intimacy 7. Unused code 8. Lazy class | data class | 0 | 10897 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 2 | 1409 | 10897 |
| 1411 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | 1. long method | t | t | t | 0 | 10900 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 1411 | 10900 | ||
| 1411 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10900 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 1411 | 10900 | |
| 1413 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | data class | t | t | t | 0 | 10905 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1413 | 10905 | ||
| 1413 | YES I found bad smells the bad smells are: 1. Long method 2. Primitive obsession 3. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Primitive obsession3 Shotgun surgery | t | f | f | . Long method2. Primitive obsession3. Shotgun surgery | data class | 0 | 10905 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1413 | 10905 |
| 1414 | YES I found bad smells the bad smells are: 1. Singleton 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Singleton2 Feature envy | t | f | f | . Singleton2. Feature envy | data class | 0 | 10909 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1414 | 10909 |
| 1417 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10917 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 2 | 1417 | 10917 |
| 1418 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 10924 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1418 | 10924 |
| 1418 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10924 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1418 | 10924 | ||
| 1419 | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | f | f | f | long method | 0 | 10925 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1419 | 10925 | |||
| 1419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10925 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1419 | 10925 | ||
| 1420 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long Method | t | f | t | 0 | 10928 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1420 | 10928 | ||
| 1420 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 10928 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1420 | 10928 | |
| 1421 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | Long Method | t | f | f | Long Method | feature envy | 0 | 10929 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1421 | 10929 |
| 1421 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10929 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1421 | 10929 | |
| 1424 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Data Class | t | f | t | 0 | 10935 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 1 | 1424 | 10935 | ||
| 1424 | YES I found bad smells the bad smells are: 1. Feature envy: The methods in the subclass all call methods in the parent class, indicating a potential problem with the OO design. 2. Long method: The methods in the subclass are all relatively long and may be difficult to understand and maintain. 3. Duplication: There is a lot of duplicated code in the methods, indicating a potential for refactoring and code reduction. 4. Primitive obsession: The methods all deal with low-level socket options, rather than abstracting them into higher-level functionality. 5. Resource acquisition is initialization (RAII) violation: The native library is loaded in the static block, rather than using RAII which is a more commonly accepted pattern in modern Java programming. 6. Inappropriate separation of responsibilities: The subclass is responsible for both defining socket options and loading the native library, which could be separated into separate classes or responsibilities for better clarity and maintainability. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Feature envy: The methods in the subclass all call methods in the parent class, indicating a potential problem with the OO design2 Long method: The methods in the subclass are all relatively long and may be difficult to understand and maintain3 Duplication: There is a lot of duplicated code in the methods, indicating a potential for refactoring and code reduction4 Primitive obsession: The methods all deal with low-level socket options, rather than abstracting them into higher-level functionality5 Resource acquisition is initialization (RAII) violation: The native library is loaded in the static block, rather than using RAII which is a more commonly accepted pattern in modern Java programming6 Inappropriate separation of responsibilities: The subclass is responsible for both defining socket options and loading the native library, which could be separated into separate classes or responsibilities for better clarity and maintainability | t | f | f | . Feature envy: The methods in the subclass all call methods in the parent class, indicating a potential problem with the OO design.2. Long method: The methods in the subclass are all relatively long and may be difficult to understand and maintain.3. Duplication: There is a lot of duplicated code in the methods, indicating a potential for refactoring and code reduction.4. Primitive obsession: The methods all deal with low-level socket options, rather than abstracting them into higher-level functionality.5. Resource acquisition is initialization (RAII) violation: The native library is loaded in the static block, rather than using RAII which is a more commonly accepted pattern in modern Java programming.6. Inappropriate separation of responsibilities: The subclass is responsible for both defining socket options and loading the native library, which could be separated into separate classes or responsibilities for better clarity and maintainability. | data class | 0 | 10935 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 2 | 1424 | 10935 |
| 1427 | { "error": "Unable to provide a valid JSON response. Please make sure to input a Java code snippet." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | Not specified | f | f | f | false | 0 | 10945 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 1 | 1427 | 10945 | |
| 1427 | * @param aggregatedModules set of already aggregated modules */ YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 10945 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 2 | 1427 | 10945 |
| 1428 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells_are": [ "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | bad_smells_are: long method | t | t | t | 0 | 10949 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 1 | 1428 | 10949 | ||
| 1428 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10949 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 2 | 1428 | 10949 | ||
| 1429 | {"status":"OK"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Not specified | f | f | f | false | 0 | 10951 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 1429 | 10951 | |
| 1429 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10951 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 1429 | 10951 | ||
| 1430 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Not specified | f | f | f | false | 0 | 10952 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 1430 | 10952 | |
| 1430 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Lack of cohesion 5. Poor exception handling 6. Nested try-catch blocks 7. Inappropriate use of if-else statements 8. Poor naming conventions (e.g. methodName, meth) 9. Too many parameters in method's signature 10. Coupled code (e.g. accessing methods and fields from other classes without proper encapsulation) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy3 Duplicate code4 Lack of cohesion5 Poor exception handling6 Nested try-catch blocks7 Inappropriate use of if-else statements8 Poor naming conventions (eg methodName, meth)9 Too many parameters in method's signature | t | f | t | meth)9. Too many parameters in method's signature | 0 | 10952 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 1430 | 10952 | |
| 1431 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method | t | t | t | 0 | 10955 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 1431 | 10955 | ||
| 1431 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10955 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 1431 | 10955 | ||
| 1432 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method, data class | t | t | t | data class | 0 | 10956 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 1432 | 10956 | |
| 1432 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Duplicate code, 4.Long parameter list, 5. Feature envy, 6. Poor variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method, 2Magic numbers, 3Duplicate code, 4Long parameter list, 5 Feature envy, 6 Poor variable naming | t | f | t | 2.Magic numbers, 3.Duplicate code, 4.Long parameter list, 5. Feature envy, 6. Poor variable naming | 0 | 10956 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 1432 | 10956 | |
| 1434 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 10959 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 2 | 1434 | 10959 |
| 1435 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method | t | t | t | 0 | 10960 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1435 | 10960 | ||
| 1435 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10960 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1435 | 10960 | ||
| 1436 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | f | f | f | long method | 0 | 10962 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 1436 | 10962 | ||
| 1436 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | Not specified | f | f | f | false | 0 | 10962 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 1436 | 10962 | |
| 1437 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 10965 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 1437 | 10965 | |
| 1437 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code (repetitive use of "if" and "else" statements) 3. Primitive obsession (hard-coded string literals and checks for null instead of proper data types) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method2 Duplicate code (repetitive use of "if" and "else" statements)3 Primitive obsession (hard-coded string literals and checks for null instead of proper data types) | t | f | t | 0 | 10965 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 1437 | 10965 | ||
| 1438 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10968 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 1438 | 10968 |
| 1438 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10968 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 1438 | 10968 |
| 1440 | {"message": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | long method | t | t | t | 0 | 10972 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 1 | 1440 | 10972 | ||
| 1440 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 10972 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 2 | 1440 | 10972 | |
| 1441 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | 1. long method | t | t | t | 0 | 10974 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 1 | 1441 | 10974 | ||
| 1441 | YES I found bad smells the bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | ) Long method2) Feature envy | t | f | t | 0 | 10974 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 2 | 1441 | 10974 | ||
| 1442 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10976 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 1442 | 10976 |
| 1442 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplicate code 5. Inconsistent naming conventions 6. Mixing of responsibilities 7. Nested if statements 8. Use of ternary operator 9. Redundant checks 10. Tight coupling between classes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | Long method2 Feature envy3 Magic numbers4 Duplicate code5 Inconsistent naming conventions6 Mixing of responsibilities7 Nested if statements8 Use of ternary operator9 Redundant checks | t | f | t | 0 | 10976 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 1442 | 10976 | ||
| 1443 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10977 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 1443 | 10977 | |
| 1443 | YES, I found bad smells the bad smells are: 1. Long Method, 2. Duplicated Code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | Long Method, 2 Duplicated Code | t | f | t | 2. Duplicated Code | 0 | 10977 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 1443 | 10977 | |
| 1444 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | 1. data class | t | t | t | 0 | 10980 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 1 | 1444 | 10980 | ||
| 1444 | YES, I found bad smells. 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10980 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 1444 | 10980 |
| 1446 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10983 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 2 | 1446 | 10983 | ||
| 1447 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | data class, long method | t | t | t | long method | 0 | 10988 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 1447 | 10988 | |
| 1447 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. God class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | Long method2 Feature envy3 Primitive obsession4 God class | t | f | f | . Long method2. Feature envy3. Primitive obsession4. God class | data class | 0 | 10988 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 1447 | 10988 |
| 1449 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | data class | t | t | t | 0 | 10991 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 1 | 1449 | 10991 | ||
| 1449 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10991 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 2 | 1449 | 10991 |
| 1450 | { "message": "YES I found bad smells", "detected_bad_smells": { "1. Data Class" : "2. Long Method" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | 1. data class: 2. long method | t | t | t | 0 | 10993 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 1 | 1450 | 10993 | ||
| 1450 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10993 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 2 | 1450 | 10993 |
| 1451 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 11000 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1451 | 11000 | ||
| 1451 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11000 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1451 | 11000 | ||
| 1452 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11001 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1452 | 11001 |
| 1452 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11001 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1452 | 11001 | ||
| 1454 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | long method, data class | t | t | t | data class | 0 | 11007 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 1 | 1454 | 11007 | |
| 1454 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11007 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 2 | 1454 | 11007 | ||
| 1459 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | feature envy, long method | t | t | t | feature envy | 0 | 11020 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1459 | 11020 | |
| 1459 | YES, I found bad smells the bad smells are: 1. Long method 2. Commented out code 3. Use of try-catch without any specific exception handling 4. Use of magic numbers/constant values 5. Feature envy (multiple methods making use of metrics from ClusterMetrics class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method2 Commented out code3 Use of try-catch without any specific exception handling4 Use of magic numbers/constant values5 Feature envy (multiple methods making use of metrics from ClusterMetrics class) | t | f | t | 0 | 11020 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1459 | 11020 | ||
| 1460 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11021 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1460 | 11021 |
| 1460 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Unclear variable names (e.g. "first", "last", "rows", "ses") 4. Poor formatting and indenting 5. Excessive commenting 6. Code duplication 7. Violation of single responsibility principle - the method is responsible for too many tasks 8. Lack of proper exception handling 9. Inefficient use of collections (e.g. using a list instead of a set) 10. Hard-coded values 11. Poor class design (e.g. too many dependencies and method calls) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | Long method2 Feature envy3 Unclear variable names (eg "first", "last", "rows", "ses")4 Poor formatting and indenting5 Excessive commenting6 Code duplication7 Violation of single responsibility principle - the method is responsible for too many tasks8 Lack of proper exception handling 9 Inefficient use of collections (eg using a list instead of a set) | t | f | t | "last", "rows", "ses")4. Poor formatting and indenting5. Excessive commenting6. Code duplication7. Violation of single responsibility principle - the method is responsible for too many tasks8. Lack of proper exception handling 9. Inefficient use of collections (e.g. using a list instead of a set) | 0 | 11021 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1460 | 11021 | |
| 1461 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | long method | t | t | t | 0 | 11023 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 1 | 1461 | 11023 | ||
| 1461 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11023 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 2 | 1461 | 11023 | |
| 1463 | {"response":"YES I found bad smells","detected_bad_smells":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | data class, long method | t | t | t | long method | 0 | 11027 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 1463 | 11027 | |
| 1463 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11027 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 1463 | 11027 |
| 1472 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
data class | Long method, 2Feature envy: | t | f | f | .Long method, 2.Feature envy: | data class | 0 | 11052 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 2 | 1472 | 11052 |
| 1474 | {"message": "YES I found bad smells\n1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Not specified | f | f | f | false | 0 | 11056 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 1474 | 11056 | |
| 1474 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11056 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 1474 | 11056 |
| 1475 | { "output": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | the bad smells are: data class | t | t | f | data class | 0 | 11062 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 1475 | 11062 | |
| 1475 | YES I found bad smells The bad smells are: 1. Data clumps 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | Data clumps2 Long method 3 Feature envy | t | f | f | . Data clumps2. Long method 3. Feature envy | data class | 0 | 11062 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 1475 | 11062 |
| 1479 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 11069 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 1479 | 11069 |
| 1480 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | data class | t | t | t | 0 | 11078 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 1 | 1480 | 11078 | ||
| 1480 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy | data class | 0 | 11078 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 2 | 1480 | 11078 |
| 1482 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | long method | t | t | f | long method | data class | 0 | 11083 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 1 | 1482 | 11083 |
| 1482 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11083 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 2 | 1482 | 11083 |
| 1484 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | long method | t | t | t | 0 | 11088 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 1484 | 11088 | ||
| 1484 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | Long method | t | f | t | 0 | 11088 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 1484 | 11088 | ||
| 1486 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11092 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 1486 | 11092 | |
| 1486 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11092 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 1486 | 11092 | ||
| 1489 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | data class, long method | t | t | t | long method | 0 | 11106 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 1 | 1489 | 11106 | |
| 1489 | YES I found bad smells the bad smells are: 1. Long method: The class has a long method called "reset" which has many lines of code and performs multiple tasks. 2. Feature envy: The class has multiple methods that access and modify the state of the class fields, indicating that they may not be encapsulated properly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | Long method: The class has a long method called "reset" which has many lines of code and performs multiple tasks2 Feature envy: The class has multiple methods that access and modify the state of the class fields, indicating that they may not be encapsulated properly | t | f | f | . Long method: The class has a long method called "reset" which has many lines of code and performs multiple tasks.2. Feature envy: The class has multiple methods that access and modify the state of the class fields, indicating that they may not be encapsulated properly. | data class | 0 | 11106 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 2 | 1489 | 11106 |
| 1490 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method | t | t | t | 0 | 11110 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1490 | 11110 | ||
| 1490 | YES I found bad smells the bad smells: 1.Split temporary variable, 2.Long method, 3.Feature envy, 4.Primitive obsession, 5.Magic numbers, 6.Inappropriate intimacy, 7.Unnecessary temporary variables, 8.Speculative generality, 9.Nested loops, 10.Duplicate code, 11.Functional decomposition, 12.Long parameter list. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Split temporary variable, 2Long method, 3Feature envy, 4Primitive obsession, 5Magic numbers, 6Inappropriate intimacy, 7Unnecessary temporary variables, 8Speculative generality, 9Nested loops, | t | f | t | .Split temporary variable, 3.Feature envy, 4.Primitive obsession, 5.Magic numbers, 6.Inappropriate intimacy, 7.Unnecessary temporary variables, 8.Speculative generality, 9.Nested loops, | 0 | 11110 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1490 | 11110 | |
| 1492 | YES I found bad smells the bad smells are: 1. Bad class name: TypeRefWithoutModifiersElements (not clear or descriptive) 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Bad class name: TypeRefWithoutModifiersElements (not clear or descriptive)2 Long method3 Feature envy | t | f | f | . Bad class name: TypeRefWithoutModifiersElements (not clear or descriptive)2. Long method3. Feature envy | data class | 0 | 11118 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1492 | 11118 |
| 1493 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11121 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 1 | 1493 | 11121 |
| 1493 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11121 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 2 | 1493 | 11121 | ||
| 1494 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | data class | t | t | t | 0 | 11123 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 1494 | 11123 | ||
| 1494 | YES I found bad smells the bad smells are: 1. Magic number (value -3096346807579L is not explained) 2. Public fields that should be private with getters/setters 3. Unused field serialVersionUID 4. Constructor with parameters that could be replaced with a default constructor and setters 5. Class name does not accurately describe its purpose or functionality 6. Lack of proper documentation/comments 7. No use of object-oriented concepts (e.g. encapsulation) 8. Serializable interface not implemented correctly or for no apparent reason. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Magic number (value -3096346807579L is not explained)2 Public fields that should be private with getters/setters3 Unused field serialVersionUID 4 Constructor with parameters that could be replaced with a default constructor and setters 5 Class name does not accurately describe its purpose or functionality 6 Lack of proper documentation/comments 7 No use of object-oriented concepts (eg encapsulation) 8 Serializable interface not implemented correctly or for no apparent reason | t | f | f | . Magic number (value -3096346807579L is not explained)2. Public fields that should be private with getters/setters3. Unused field serialVersionUID 4. Constructor with parameters that could be replaced with a default constructor and setters 5. Class name does not accurately describe its purpose or functionality 6. Lack of proper documentation/comments 7. No use of object-oriented concepts (e.g. encapsulation) 8. Serializable interface not implemented correctly or for no apparent reason. | data class | 0 | 11123 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 1494 | 11123 |
| 1495 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11124 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1495 | 11124 | |
| 1495 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11124 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1495 | 11124 | |
| 1496 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11125 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1496 | 11125 |
| 1496 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11125 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1496 | 11125 | ||
| 1497 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | long method | t | t | t | 0 | 11126 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1497 | 11126 | ||
| 1497 | YES I found bad smells The bad smells are: 1. Long method 2. Magic string 3. Repeated code 4. Lack of abstraction 5. Feature envy 6. Large block of code 7. Poorly named variables and methods 8. Explicit type declaration (should use var instead) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method2 Magic string3 Repeated code4 Lack of abstraction5 Feature envy6 Large block of code7 Poorly named variables and methods8 Explicit type declaration (should use var instead) | t | f | t | 0 | 11126 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1497 | 11126 | ||
| 1498 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11127 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1498 | 11127 |
| 1498 | YES, I found bad smells the bad smells are: 1. Long method list any bad smell. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
feature envy | Long methodlist any bad smellNO, I did not find any bad smell | t | f | f | . Long methodlist any bad smell.NO, I did not find any bad smell. | feature envy | 0 | 11127 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1498 | 11127 |
| 1501 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11134 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 1501 | 11134 |
| 1501 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 11134 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 1501 | 11134 | ||
| 1502 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | long method, data class | t | t | t | data class | 0 | 11135 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 1502 | 11135 | |
| 1502 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Complex conditional statements 6. Nested loops 7. Unnecessary try-catch blocks 8. Inadequate exception handling 9. Inconsistent indentation and formatting 10. Poor variable naming 11. Code comments that are unclear or obsolete 12. Lack of modularity and separation of concerns 13. Too many responsibilities for a single method 14. Use of outdated Java language features | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method2 Feature envy3 Code duplication4 Inconsistent naming conventions5 Complex conditional statements6 Nested loops7 Unnecessary try-catch blocks8 Inadequate exception handling9 Inconsistent indentation and formatting | t | f | t | 0 | 11135 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 1502 | 11135 | ||
| 1503 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11136 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 1503 | 11136 |
| 1503 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11136 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 1503 | 11136 | ||
| 1505 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | data class | t | t | t | 0 | 11149 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 1 | 1505 | 11149 | ||
| 1505 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | f | f | f | data class | 0 | 11149 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 2 | 1505 | 11149 | ||
| 1506 | { "output": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | data class | t | t | t | 0 | 11150 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1506 | 11150 | ||
| 1506 | YES, I found bad smellsthe bad smells are: 1. Getter and setter methods for all variables. 2. Class name is not descriptive. 3. Code is not following SOLID principles. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Getter and setter methods for all variables2 Class name is not descriptive3 Code is not following SOLID principles | t | f | f | . Getter and setter methods for all variables.2. Class name is not descriptive.3. Code is not following SOLID principles. | data class | 0 | 11150 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1506 | 11150 |
| 1512 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11160 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1512 | 11160 |
| 1512 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Repeated code, 3. Feature envy, 4. Nested if statements, 5. Catch blocks for multiple exceptions, 6. Use of primitive types instead of reference types, 7. Use of unnecessary temporary variables, 8. Inconsistent naming convention, 9. Mixing business logic with data retrieval, 10. Lack of comments explaining complex logic. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
feature envy | Long method, 2 Repeated code, 3 Feature envy, 4 Nested if statements, 5 Catch blocks for multiple exceptions, 6 Use of primitive types instead of reference types, 7 Use of unnecessary temporary variables, 8 Inconsistent naming convention, 9 Mixing business logic with data retrieval, | t | f | t | . Long method, 2. Repeated code, 4. Nested if statements, 5. Catch blocks for multiple exceptions, 6. Use of primitive types instead of reference types, 7. Use of unnecessary temporary variables, 8. Inconsistent naming convention, 9. Mixing business logic with data retrieval, | 0 | 11160 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1512 | 11160 | |
| 1513 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11161 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1513 | 11161 | |
| 1513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11161 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1513 | 11161 | ||
| 1515 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11164 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1515 | 11164 | |
| 1515 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11164 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1515 | 11164 | ||
| 1516 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 11165 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1516 | 11165 | |
| 1516 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11165 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1516 | 11165 | ||
| 1518 | {"response": "YES, I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | t | f | f | long method | 0 | 11170 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 1518 | 11170 | ||
| 1518 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11170 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 1518 | 11170 | ||
| 1519 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11171 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 1519 | 11171 | ||
| 1520 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method | t | t | t | 0 | 11172 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1520 | 11172 | ||
| 1520 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11172 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1520 | 11172 | ||
| 1521 | { "message": "YES I found bad smells", "detected_bad_smells": { "1. Long Method": {}, "2. Feature Envy": {} } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | t | f | f | feature envy | 0 | 11173 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1521 | 11173 | ||
| 1521 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11173 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1521 | 11173 | ||
| 1522 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11174 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 2 | 1522 | 11174 |
| 1523 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long Method | t | f | t | 0 | 11179 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 1 | 1523 | 11179 | ||
| 1523 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11179 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 2 | 1523 | 11179 | ||
| 1524 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Data Class | t | f | t | 0 | 11182 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 1 | 1524 | 11182 | ||
| 1524 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11182 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 2 | 1524 | 11182 |
| 1526 | { "answer": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Data Class | t | f | t | 0 | 11186 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 1 | 1526 | 11186 | ||
| 1526 | YES, I found bad smells. the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11186 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 2 | 1526 | 11186 |
| 1527 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Data Class | t | f | t | 0 | 11193 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 1527 | 11193 | ||
| 1527 | YES I found bad smells the bad smells are: 1. Long method 2. No comments or documentation 3. Use of abstract class with only one concrete subclass 4. Use of raw types in superclass 5. Redundant use of final keyword 6. Lack of information in variable names (e.g. "source", "messageId") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Long method2 No comments or documentation3 Use of abstract class with only one concrete subclass4 Use of raw types in superclass5 Redundant use of final keyword6 Lack of information in variable names (eg "source", "messageId") | t | f | f | . Long method2. No comments or documentation3. Use of abstract class with only one concrete subclass4. Use of raw types in superclass5. Redundant use of final keyword6. Lack of information in variable names (e.g. "source", "messageId") | data class | 0 | 11193 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 1527 | 11193 |
| 1528 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11199 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 1 | 1528 | 11199 | |
| 1528 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11199 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 2 | 1528 | 11199 | |
| 1530 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
data class | long method | t | t | f | long method | data class | 0 | 11205 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 1 | 1530 | 11205 |
| 1530 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 11205 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 2 | 1530 | 11205 |
| 1532 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 11209 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 2 | 1532 | 11209 |
| 1532 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | data class | 0 | 11209 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 1532 | 11209 |
| 1536 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | Data Class | t | f | t | 0 | 11219 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 1 | 1536 | 11219 | ||
| 1536 | YES, I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 11219 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 1536 | 11219 |
| 1537 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | t | f | f | long method | 0 | 11223 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 1537 | 11223 | ||
| 1537 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11223 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 1537 | 11223 | ||
| 1538 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11226 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 1538 | 11226 | |
| 1538 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11226 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 1538 | 11226 | ||
| 1543 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11243 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 1543 | 11243 | |
| 1543 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11243 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 1543 | 11243 | ||
| 1544 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long Method | t | f | t | 0 | 11245 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1544 | 11245 | ||
| 1544 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11245 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1544 | 11245 | ||
| 1547 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long Method | t | f | t | 0 | 11256 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 1547 | 11256 | ||
| 1547 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions (some elements and attributes use uppercase while others use lowercase) 4. Magic numbers (numerical values assigned without explanation) 5. Use of ArrayList instead of List interface 6. Use of comment block instead of proper documentation 7. Overloaded constructor with multiple arguments 8. Boolean flag parameters in addAttribute() method 9. Large number of parameters in addElement() and addAttribute() methods 10. Hard-coded values instead of using constants or variables 11. Unused variables/reserved word "res" 12. Poorly named variables (e.g. "cod | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy3 Inconsistent naming conventions (some elements and attributes use uppercase while others use lowercase)4 Magic numbers (numerical values assigned without explanation)5 Use of ArrayList instead of List interface6 Use of comment block instead of proper documentation 7 Overloaded constructor with multiple arguments 8 Boolean flag parameters in addAttribute() method 9 Large number of parameters in addElement() and addAttribute() methods | t | f | t | 0 | 11256 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 1547 | 11256 | ||
| 1548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11258 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1548 | 11258 | |
| 1548 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11258 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1548 | 11258 | ||
| 1551 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11265 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 1551 | 11265 | ||
| 1551 | NO, I did not find any bad smell in the given code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11265 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 1551 | 11265 | ||
| 1552 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long Method | t | f | t | 0 | 11269 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 1 | 1552 | 11269 | ||
| 1552 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Nested conditionals 4. Inconsistent variable naming 5. Unused code 6. Inappropriate naming (e.g. delegate, parent) 7. Complex nested operations 8. Mixed responsibilities (handling XML and DOM implementation separately) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long method2 Feature Envy3 Nested conditionals4 Inconsistent variable naming5 Unused code6 Inappropriate naming (eg delegate, parent)7 Complex nested operations 8 Mixed responsibilities (handling XML and DOM implementation separately) | t | f | t | parent)7. Complex nested operations 8. Mixed responsibilities (handling XML and DOM implementation separately) | 0 | 11269 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 2 | 1552 | 11269 | |
| 1555 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long Method | t | f | t | 0 | 11276 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 1 | 1555 | 11276 | ||
| 1555 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11276 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 2 | 1555 | 11276 | ||
| 1559 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the if conditions for different instances of Length) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy3 Duplicate code (in the if conditions for different instances of Length) | t | f | t | 0 | 11300 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1559 | 11300 | ||
| 1561 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long Method | t | f | t | 0 | 11308 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 1561 | 11308 | ||
| 1561 | YES I found bad smells the bad smells are: 1. Long method 2. Inconsistent indentation 3. Empty catch statement 4. Magic numbers 5. Use of switch statement 6. Use of multiple if/else statements 7. Use of null check syntax 8. Code duplication/repetition 9. Poor variable naming 10. Mixing of logic and data manipulation 11. Unnecessary commenting 12. Nested conditionals 13. Hard-coded values 14. Mix of different coding styles/mixing of languages (Java and protocols) 15. Use of bitwise operations (bitField0_) 16. Lack of proper error handling/reporting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Inconsistent indentation3 Empty catch statement4 Magic numbers5 Use of switch statement6 Use of multiple if/else statements7 Use of null check syntax8 Code duplication/repetition9 Poor variable naming | t | f | t | 0 | 11308 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 1561 | 11308 | ||
| 1562 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Data Class | t | f | t | 0 | 11312 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 1 | 1562 | 11312 | ||
| 1562 | YES I found bad smells. The bad smells are: 1. Long parameter list. 2. Primitive obsession. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Long parameter list 2 Primitive obsession | t | f | f | . Long parameter list. 2. Primitive obsession. | data class | 0 | 11312 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 2 | 1562 | 11312 |
| 1563 | {"response": "YES I found bad smells the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | t | f | f | data class | 0 | 11316 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 1563 | 11316 | ||
| 1563 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11316 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 1563 | 11316 |
| 1564 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11320 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 1 | 1564 | 11320 | |
| 1564 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11320 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 2 | 1564 | 11320 |
| 1566 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11327 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 1566 | 11327 |
| 1566 | YES I found bad smells 1. Magic number (currently not used) 2. Unused variables (sysDir, stagingAreaDir, jobHistoryDir) 3. Long method (initialize, close, getFileSystem, getJob) 4. Feature envy (ClientProtocol, UserGroupInformation, Configuration) 5. Inappropriate static method (loadResources) 6. Empty catch block (catch (Exception e)) 7. Unused imports (@InterfaceAudience, @InterfaceStability) 8. Tightly coupled code (synchronized block in initialize method) 9. Inconsistent coding style (some methods are camelCase and some are underscore_separated) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Magic number (currently not used)2 Unused variables (sysDir, stagingAreaDir, jobHistoryDir)3 Long method (initialize, close, getFileSystem, getJob)4 Feature envy (ClientProtocol, UserGroupInformation, Configuration)5 Inappropriate static method (loadResources)6 Empty catch block (catch (Exception e))7 Unused imports (@InterfaceAudience, @InterfaceStability)8 Tightly coupled code (synchronized block in initialize method)9 Inconsistent coding style (some methods are camelCase and some are underscore_separated) | t | f | f | . Magic number (currently not used)2. Unused variables (sysDir, stagingAreaDir, jobHistoryDir)3. Long method (initialize, close, getFileSystem, getJob)4. Feature envy (ClientProtocol, UserGroupInformation, Configuration)5. Inappropriate static method (loadResources)6. Empty catch block (catch (Exception e))7. Unused imports (@InterfaceAudience, @InterfaceStability)8. Tightly coupled code (synchronized block in initialize method)9. Inconsistent coding style (some methods are camelCase and some are underscore_separated) | data class | 0 | 11327 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 1566 | 11327 |
| 1567 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | long method, data class | t | t | t | long method | 0 | 11329 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 1567 | 11329 | |
| 1567 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11329 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 1567 | 11329 |
| 1568 | {"response": "YES I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | 1. data class | t | t | t | 0 | 11331 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 1 | 1568 | 11331 | ||
| 1568 | YES I found bad smells The bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 11331 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 2 | 1568 | 11331 |
| 1570 | {"response": "YES I found bad smells", "bad smells are:": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | long method | t | t | f | long method | data class | 0 | 11335 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 2 | 1570 | 11335 |
| 1571 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11339 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 1 | 1571 | 11339 |
| 1571 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11339 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 2 | 1571 | 11339 |
| 1572 | {"message": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Feature Envy | t | f | f | Feature Envy | long method | 0 | 11341 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 1572 | 11341 |
| 1572 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11341 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 1572 | 11341 | |
| 1575 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Data Class | t | f | t | 0 | 11348 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 1 | 1575 | 11348 | ||
| 1575 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11348 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 2 | 1575 | 11348 |
| 1576 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | Data Class | t | f | t | 0 | 11350 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 1 | 1576 | 11350 | ||
| 1576 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11350 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 2 | 1576 | 11350 |
| 1577 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 11353 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 1 | 1577 | 11353 |
| 1577 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 11353 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 2 | 1577 | 11353 |
| 1580 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | long method, data class | t | t | t | data class | 0 | 11359 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 1 | 1580 | 11359 | |
| 1580 | " YES I found bad smells" The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11359 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 2 | 1580 | 11359 | |
| 1581 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | t | f | f | data class | 0 | 11362 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 1581 | 11362 | ||
| 1581 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate coupling 3. Feature envy 4. Duplicated code 5. Magic numbers 6. Dead code 7. Misplaced responsibility 8. Inconsistent naming 9. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | Long method 2 Inappropriate coupling 3 Feature envy 4 Duplicated code 5 Magic numbers 6 Dead code 7 Misplaced responsibility 8 Inconsistent naming 9 Data class | t | f | t | 0 | 11362 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 1581 | 11362 | ||
| 1583 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | f | f | f | long method | 0 | 11365 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 1583 | 11365 | ||
| 1583 | Yes I found bad smells: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Complex conditional logic (if statements nested within other if statements), 5. Misleading comments (commented out code that is not being used), 6. Manual exception handling rather than using a try-catch block. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Complex conditional logic (if statements nested within other if statements), 5 Misleading comments (commented out code that is not being used), 6 Manual exception handling rather than using a try-catch block | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Complex conditional logic (if statements nested within other if statements), 5. Misleading comments (commented out code that is not being used), 6. Manual exception handling rather than using a try-catch block. | 0 | 11365 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 1583 | 11365 | |
| 1587 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
long method | long method, data class | t | t | t | data class | 0 | 11373 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 1 | 1587 | 11373 | |
| 1587 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Code duplication 4. Lack of comments/documentation 5. Poor variable naming/descriptive names 6. Code that is difficult to understand/maintain 7. Potential violation of single responsibility principle 8. Potential catch-all exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
long method | Feature envy2 Long method3 Code duplication4 Lack of comments/documentation5 Poor variable naming/descriptive names6 Code that is difficult to understand/maintain7 Potential violation of single responsibility principle 8 Potential catch-all exception handling | t | f | t | 0 | 11373 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 2 | 1587 | 11373 | ||
| 1588 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | long method | t | t | t | 0 | 11376 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 1 | 1588 | 11376 | ||
| 1588 | YES I found bad smells The bad smells are: 1.Method with multiple responsibilities 2. Complex conditional logic 3. Long method 4. Feature envy 5. Duplicate code 6. Dependency on specific implementation 7. Dependency on specific feature | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | Method with multiple responsibilities2 Complex conditional logic3 Long method4 Feature envy5 Duplicate code6 Dependency on specific implementation7 Dependency on specific feature | t | f | t | 0 | 11376 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 2 | 1588 | 11376 | ||
| 1589 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Data Class | t | f | t | 0 | 11385 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 1589 | 11385 | ||
| 1589 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11385 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 1589 | 11385 |
| 1590 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | 1 Long Method | t | f | t | 0 | 11387 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 1 | 1590 | 11387 | ||
| 1590 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11387 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 2 | 1590 | 11387 | ||
| 1592 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
long method | t | f | f | long method | 0 | 11396 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 1 | 1592 | 11396 | ||
| 1592 | YES I found bad smells the bad smells are: 1.Long method, 2.Duplicated Code, 3.Complex method, 4.Long parameter list, 5.Magic numbers, 6.Inappropriate comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
long method | Long method, 2Duplicated Code, 3Complex method, 4Long parameter list, 5Magic numbers, 6Inappropriate comments | t | f | t | 2.Duplicated Code, 3.Complex method, 4.Long parameter list, 5.Magic numbers, 6.Inappropriate comments. | 0 | 11396 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 2 | 1592 | 11396 | |
| 1594 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11407 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 1594 | 11407 |
| 1595 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11408 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 1595 | 11408 | |
| 1595 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Poor variable and method naming 4. Unnecessary commenting 5. Use of instanceof 6. Nested if/else blocks 7. Lack of proper comparison "strategy" 8. Unnecessary casting 9. Lack of clear separation of tasks/responsibilities 10. Possible code duplication 11. Missing error handling 12. Potential for null pointer exceptions 13. Lack of use of standard equals() method 14. Excessive amount of code wrapping | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long method 2 Feature envy 3 Poor variable and method naming 4 Unnecessary commenting 5 Use of instanceof 6 Nested if/else blocks 7 Lack of proper comparison "strategy" 8 Unnecessary casting 9 Lack of clear separation of tasks/responsibilities | t | f | t | 0 | 11408 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 1595 | 11408 | ||
| 1596 | { "output": "YES I found bad smells the bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | t | f | f | data class | 0 | 11413 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 1 | 1596 | 11413 | ||
| 1596 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11413 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 2 | 1596 | 11413 |
| 1598 | {"response": "YES I found bad smells the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | t | f | f | data class | 0 | 11417 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 1598 | 11417 | ||
| 1598 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11417 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 1598 | 11417 |
| 1601 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Data Class | t | f | t | 0 | 11429 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 1601 | 11429 | ||
| 1601 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11429 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 1601 | 11429 |
| 1603 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long Method | t | f | t | 0 | 11438 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1603 | 11438 | ||
| 1603 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11438 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1603 | 11438 | ||
| 1604 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | 1 Long Method, 2 Data Class | t | f | t | 2. Data Class | 0 | 11442 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 1604 | 11442 | |
| 1604 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11442 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 1604 | 11442 | |
| 1609 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | 1 Data Class | t | f | t | 0 | 11456 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 1 | 1609 | 11456 | ||
| 1609 | YES I found bad smells 1. Data Clumps - the fields name and classLoaderId seem to be frequently used together in the code. 2. Primitive Obsession - the field instrClassId is an integer instead of a dedicated class. 3. Long Parameter List - the constructor has two parameters which could potentially be reduced. 4. Feature Envy - the methods setInstrClassId() and getInstrClassId() seem to be residing in the wrong class. 5. Inappropriate Intimacy - the constructor modifies the external objects classLoaderId and name, suggesting a close relationship between the classes. 6. Temporary Field - the field instrClassId is only used temporarily for instrumentation purposes. 7. Highly Coupled Classes - the class BaseClassInfo depends heavily on the class loader mechanism and its related fields and methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | Data Clumps - the fields name and classLoaderId seem to be frequently used together in the code2 Primitive Obsession - the field instrClassId is an integer instead of a dedicated class3 Long Parameter List - the constructor has two parameters which could potentially be reduced4 Feature Envy - the methods setInstrClassId() and getInstrClassId() seem to be residing in the wrong class5 Inappropriate Intimacy - the constructor modifies the external objects classLoaderId and name, suggesting a close relationship between the classes6 Temporary Field - the field instrClassId is only used temporarily for instrumentation purposes7 Highly Coupled Classes - the class BaseClassInfo depends heavily on the class loader mechanism and its related fields and methods | t | f | f | . Data Clumps - the fields name and classLoaderId seem to be frequently used together in the code.2. Primitive Obsession - the field instrClassId is an integer instead of a dedicated class.3. Long Parameter List - the constructor has two parameters which could potentially be reduced.4. Feature Envy - the methods setInstrClassId() and getInstrClassId() seem to be residing in the wrong class.5. Inappropriate Intimacy - the constructor modifies the external objects classLoaderId and name, suggesting a close relationship between the classes.6. Temporary Field - the field instrClassId is only used temporarily for instrumentation purposes.7. Highly Coupled Classes - the class BaseClassInfo depends heavily on the class loader mechanism and its related fields and methods. | data class | 0 | 11456 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 2 | 1609 | 11456 |
| 1611 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | f | f | f | data class | 0 | 11463 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 1 | 1611 | 11463 | ||
| 1611 | YES, I found bad smells The bad smells are: 1. Class not well-structured 2. Class fields not organized 3. No constructor or getter/setter methods 4. Inconsistent formatting of field declarations (some have equal signs, some have semi-colons) 5. Fields not marked as private or not properly encapsulated | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | Class not well-structured2 Class fields not organized3 No constructor or getter/setter methods4 Inconsistent formatting of field declarations (some have equal signs, some have semi-colons)5 Fields not marked as private or not properly encapsulated | t | f | f | . Class not well-structured2. Class fields not organized3. No constructor or getter/setter methods4. Inconsistent formatting of field declarations (some have equal signs, some have semi-colons)5. Fields not marked as private or not properly encapsulated | data class | 0 | 11463 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 2 | 1611 | 11463 |
| 1612 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Data Class | t | f | t | 0 | 11467 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 1612 | 11467 | ||
| 1612 | YES I found bad smells. The bad smells are: 1. Lack of comments/documentation. 2. Class name does not accurately describe its purpose/function. 3. Method names do not accurately describe their purpose/function. 4. Getter and setter methods are not necessary for this class. 5. Variables are not declared as private. 6. Constructor is not necessary for this class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Lack of comments/documentation2 Class name does not accurately describe its purpose/function3 Method names do not accurately describe their purpose/function4 Getter and setter methods are not necessary for this class5 Variables are not declared as private6 Constructor is not necessary for this class | t | f | f | . Lack of comments/documentation.2. Class name does not accurately describe its purpose/function.3. Method names do not accurately describe their purpose/function.4. Getter and setter methods are not necessary for this class.5. Variables are not declared as private.6. Constructor is not necessary for this class. | data class | 0 | 11467 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 1612 | 11467 |
| 1613 | { "message": "YES, I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | t | f | f | long method | 0 | 11470 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 1613 | 11470 | ||
| 1613 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (the code is manipulating data belonging to the connection object instead of its own data) 3. Magic numbers/strings (e.g. -1, "Connection error while authenticating user") 4. Hard coded values (e.g. Version.CURRENT) 5. Code duplication (setting the secure part of the message twice) 6. Inconsistent formatting and indentation 7. Lack of proper error handling and comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | Long method2 Feature envy (the code is manipulating data belonging to the connection object instead of its own data) 3 Magic numbers/strings (eg - | t | f | t | 0 | 11470 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 1613 | 11470 | ||
| 1614 | {"message": "YES, I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
feature envy | t | f | f | feature envy | 0 | 11471 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 1614 | 11471 | ||
| 1614 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11471 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 1614 | 11471 | ||
| 1615 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Data Class, Long Method | t | f | t | Data Class | 0 | 11472 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 1615 | 11472 | |
| 1615 | YES I found bad smells The bad smells are: 1. Duplicate code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Duplicate code 2 Long method 3 Feature envy | t | f | t | 0 | 11472 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 1615 | 11472 | ||
| 1618 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 11476 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1618 | 11476 |
| 1618 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Useless comments 6. Lack of proper variable and function names 7. Complex code without proper explanation/comments 8. Inefficient code structure 9. Code repetition 10. Unnecessary complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
feature envy | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Useless comments6 Lack of proper variable and function names7 Complex code without proper explanation/comments8 Inefficient code structure9 Code repetition | t | f | t | 0 | 11476 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1618 | 11476 | ||
| 1619 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11477 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1619 | 11477 | |
| 1619 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11477 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1619 | 11477 | ||
| 1620 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | Data Class | t | f | t | 0 | 11479 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 1 | 1620 | 11479 | ||
| 1620 | YES I found bad smells.The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 11479 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 2 | 1620 | 11479 |
| 1621 | { "message": "YES, I found bad smells", "bad_smells_are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | t | f | f | data class | 0 | 11483 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 1 | 1621 | 11483 | ||
| 1621 | YES I found bad smells. The bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy. | data class | 0 | 11483 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 2 | 1621 | 11483 |
| 1623 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
long method | 1 Long Method | t | f | t | 0 | 11490 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 1 | 1623 | 11490 | ||
| 1623 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11490 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 2 | 1623 | 11490 | ||
| 1625 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11499 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 1 | 1625 | 11499 |
| 1625 | YES I found bad smells 1. Long method 2. Long parameter list 3. Feature envy 4. Indecent exposure 5. Speculative generality | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 Long parameter list3 Feature envy4 Indecent exposure5 Speculative generality | t | f | f | . Long method2. Long parameter list3. Feature envy4. Indecent exposure5. Speculative generality | data class | 0 | 11499 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 2 | 1625 | 11499 |
| 1626 | {"output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | Long Method, 2 Data Class"} | t | f | t | . Long Method | 0 | 11500 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 1 | 1626 | 11500 | |
| 1626 | {"response":"YES I found bad smells","the bad smells are":["Long method","Deprecated field","Low cohesion","Feature envy","Long parameter list","Data class","Large class","Message chains","Inappropriate intimacy","Data clumps","Long class"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | long method, deprecated field, low cohesion, feature envy, long parameter list, data class, large class, message chains, inappropriate intimacy, data clumps, long class | t | t | t | long method, deprecated field, low cohesion, feature envy, long parameter list, large class, message chains, inappropriate intimacy, data clumps, long class | 0 | 11500 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 2 | 1626 | 11500 | |
| 1629 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11503 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 1629 | 11503 |
| 1632 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11512 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 1 | 1632 | 11512 |
| 1632 | YES I found bad smells the bad smells are: 1. SuppressWarnings 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | SuppressWarnings2 Long method | t | f | f | . SuppressWarnings2. Long method | data class | 0 | 11512 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 2 | 1632 | 11512 |
| 1633 | { "output": "YES I found bad smells\nthe bad smells are: 1. Data class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | 1. data class | t | t | t | 0 | 11514 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 1633 | 11514 | ||
| 1635 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11522 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1635 | 11522 | |
| 1635 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11522 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1635 | 11522 | ||
| 1636 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long Method | t | f | t | 0 | 11525 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 1 | 1636 | 11525 | ||
| 1636 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11525 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 2 | 1636 | 11525 | ||
| 1637 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11527 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 1637 | 11527 | ||
| 1639 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11533 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 2 | 1639 | 11533 | ||
| 1639 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11533 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 1 | 1639 | 11533 | ||
| 1640 | {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
data class | data class, long method | t | t | t | long method | 0 | 11534 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 1 | 1640 | 11534 | |
| 1642 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells": [ "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | bad_smells, Long Method | t | f | f | bad_smells, Long Method | data class | 0 | 11545 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 1 | 1642 | 11545 |
| 1642 | YES, I found bad smells: 1. Redundant variable "cGroup" and "cNameAssignment_0" 2. Redundant variable "cGroup_1" and "cTypeAssignment_1_1" 3. Redundant variable "cColonKeyword_1_0" 4. Redundant method "getRule()" 5. Redundant method "getGroup()" 6. Redundant method "getNameAssignment_0()" 7. Redundant method "getNameIdentifierParserRuleCall_0_0()" 8. Redundant method "getGroup_1()" 9. Redundant method "getColonKeyword_1_0()" 10. Redundant method "getTypeAssignment_1_1()" 11. Redundant method "getTypeTypeExpParserRuleCall_1_1_0()" 12. Possible feature envy with "getGrammar()" 13. Long method with multiple assignments and inefficient code structure. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | Redundant variable "cGroup" and "cNameAssignment_0"2 Redundant variable "cGroup_ | t | f | f | . Redundant variable "cGroup" and "cNameAssignment_0"2. Redundant variable "cGroup_ | data class | 0 | 11545 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 2 | 1642 | 11545 |
| 1644 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long Method | t | f | t | 0 | 11558 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1644 | 11558 | ||
| 1644 | YES I found bad smells The bad smells are: 1. Long method 2. Magic numbers 3. Complex conditionals 4. Feature envy 5. Large switch statement 6. Hard-coded values 7. Bad exception handling 8. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Magic numbers3 Complex conditionals4 Feature envy5 Large switch statement6 Hard-coded values7 Bad exception handling8 Code duplication | t | f | t | 0 | 11558 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1644 | 11558 | ||
| 1646 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11562 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1646 | 11562 |
| 1646 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Large class 5. Indecent exposure (due to multiple public variables) 6. Combinatorial explosion (due to nested loops) 7. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
feature envy | Long method2 Feature envy3 Duplicated code4 Large class5 Indecent exposure (due to multiple public variables)6 Combinatorial explosion (due to nested loops)7 Lazy class | t | f | t | 0 | 11562 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1646 | 11562 | ||
| 1647 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | long method | t | t | t | 0 | 11563 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1647 | 11563 | ||
| 1647 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Inefficient looping 5. Inconsistent naming conventions 6. Lack of encapsulation/modularity 7. Inconsistent use of synchronized blocks 8. Complex conditional statements within loops 9. Use of break/continue statements 10. Lack of proper commenting/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | Long method2 Feature envy3 Primitive obsession4 Inefficient looping5 Inconsistent naming conventions 6 Lack of encapsulation/modularity 7 Inconsistent use of synchronized blocks 8 Complex conditional statements within loops 9 Use of break/continue statements | t | f | t | 0 | 11563 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1647 | 11563 | ||
| 1648 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | 1. data class | t | t | f | 1. data class | feature envy | 0 | 11565 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 1 | 1648 | 11565 |
| 1648 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | Long method | t | f | f | .Long method | feature envy | 0 | 11565 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 2 | 1648 | 11565 |
| 1650 | { "output": "YES I found bad smells. the bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | t | f | f | data class | 0 | 11573 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 1 | 1650 | 11573 | ||
| 1650 | YES I found bad smells the bad smells are: 1. Inconsistent naming conventions (e.g. getName and setName instead of getX and setX) 2. Lack of constructor with parameters, leading to an empty constructor 3. Use of raw types instead of specifying the type of elements in the Map 4. No validation or error handling in the setter methods 5. No encapsulation of variables, as they are directly accessible through getters and setters without any validation or control over their values | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | Inconsistent naming conventions (eg getName and setName instead of getX and setX)2 Lack of constructor with parameters, leading to an empty constructor3 Use of raw types instead of specifying the type of elements in the Map4 No validation or error handling in the setter methods5 No encapsulation of variables, as they are directly accessible through getters and setters without any validation or control over their values | t | f | f | . Inconsistent naming conventions (e.g. getName and setName instead of getX and setX)2. Lack of constructor with parameters, leading to an empty constructor3. Use of raw types instead of specifying the type of elements in the Map4. No validation or error handling in the setter methods5. No encapsulation of variables, as they are directly accessible through getters and setters without any validation or control over their values | data class | 0 | 11573 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 2 | 1650 | 11573 |
| 1651 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | 1 Long Method, 2 Data Class | t | f | t | 2. Data Class | 0 | 11579 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 1651 | 11579 | |
| 1651 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11579 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 1651 | 11579 | ||
| 1652 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 1652 | 11582 | |
| 1652 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1652 | 11582 |
| 1653 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 11584 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 1653 | 11584 | |
| 1653 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11584 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 1653 | 11584 | ||
| 1654 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11585 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 1654 | 11585 | |
| 1654 | YES I found bad smells the bad smells are: 1. Feature envy, 2. Long method, 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Feature envy, 2 Long method, 3 Duplicate code | t | f | t | . Feature envy, 3. Duplicate code | 0 | 11585 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 1654 | 11585 | |
| 1655 | {"response": "YES I found bad smells the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | t | f | f | data class | 0 | 11587 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 1 | 1655 | 11587 | ||
| 1655 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11587 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 2 | 1655 | 11587 |
| 1657 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11601 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 1657 | 11601 | |
| 1657 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11601 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 1657 | 11601 | ||
| 1658 | {"response": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | t | f | f | data class | 0 | 11602 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 1 | 1658 | 11602 | ||
| 1658 | YES I found bad smells the bad smells are: 1. Duplication of code between PersistenceWithIntOffset and PersistenceWithIntOffsetNoLL 2. Unnecessary use of "protected" modifier for the class 3. Confusing and unclear comments 4. Inconsistent formatting and spacing 5. Poor variable naming (ex. prev, next, v) 6. Direct access of instance variables without encapsulation or getter/setter methods 7. Unused methods (setPrev, setNext) 8. Potential for Feature Envy - PersistenceWithIntOffset has direct access to and modifies the instance variables of DiskEntry, which could be considered a separate entity. 9. Potential for Long Method - depending on the functionality being performed in the methods, they may be lengthy and complex. However, without a clear understanding of the context and purpose of this code, it is difficult to determine for certain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | Duplication of code between PersistenceWithIntOffset and PersistenceWithIntOffsetNoLL2 Unnecessary use of "protected" modifier for the class3 Confusing and unclear comments4 Inconsistent formatting and spacing5 Poor variable naming (ex prev, next, v) 6 Direct access of instance variables without encapsulation or getter/setter methods7 Unused methods (setPrev, setNext)8 Potential for Feature Envy - PersistenceWithIntOffset has direct access to and modifies the instance variables of DiskEntry, which could be considered a separate entity9 Potential for Long Method - depending on the functionality being performed in the methods, they may be lengthy and complex However, without a clear understanding of the context and purpose of this code, it is difficult to determine for certain | t | f | f | . Duplication of code between PersistenceWithIntOffset and PersistenceWithIntOffsetNoLL2. Unnecessary use of "protected" modifier for the class3. Confusing and unclear comments4. Inconsistent formatting and spacing5. Poor variable naming (ex. prev, next, v) 6. Direct access of instance variables without encapsulation or getter/setter methods7. Unused methods (setPrev, setNext)8. Potential for Feature Envy - PersistenceWithIntOffset has direct access to and modifies the instance variables of DiskEntry, which could be considered a separate entity.9. Potential for Long Method - depending on the functionality being performed in the methods, they may be lengthy and complex. However, without a clear understanding of the context and purpose of this code, it is difficult to determine for certain. | data class | 0 | 11602 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 2 | 1658 | 11602 |
| 1659 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | 1 Data Class | t | f | t | 0 | 11607 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 1659 | 11607 | ||
| 1659 | YES I found bad smells The bad smells are: 1. Empty constructor 2. Public fields | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Empty constructor2 Public fields | t | f | f | . Empty constructor2. Public fields | data class | 0 | 11607 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 1659 | 11607 |
| 1660 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long Method | t | f | t | 0 | 11609 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 1660 | 11609 | ||
| 1660 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy: The method uses multiple different objects from external classes, indicating a possible violation of encapsulation and dependency issues. 3. Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent. 4. Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method2 Feature envy: The method uses multiple different objects from external classes, indicating a possible violation of encapsulation and dependency issues 3 Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent 4 Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging | t | f | t | indicating a possible violation of encapsulation and dependency issues. 3. Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent. 4. Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging. | 0 | 11609 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 1660 | 11609 | |
| 1662 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Data Class | t | f | t | 0 | 11614 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1662 | 11614 | ||
| 1662 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11614 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1662 | 11614 |
| 1665 | { "output": { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11622 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1665 | 11622 | |
| 1665 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11622 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1665 | 11622 | ||
| 1666 | { "response": "YES I found bad smells", "bad smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | t | f | f | feature envy | 0 | 11623 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1666 | 11623 | ||
| 1666 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 11623 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1666 | 11623 | ||
| 1672 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 11637 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1672 | 11637 |
| 1672 | YES I found bad smells 1. Long method 2. Data class 3. Shotgun surgery 4. Inappropriate intimacy 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Long method2 Data class3 Shotgun surgery4 Inappropriate intimacy5 Feature envy | t | f | t | 0 | 11637 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1672 | 11637 | ||
| 1674 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | data class | t | t | t | 0 | 11643 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 1674 | 11643 | ||
| 1674 | YES I found bad smells The bad smells are: 1. Feature envy: The Mina2Configuration class contains a lot of getters and setters for the various options, which shows that functionality is probably spread out among different classes. 2. Long method: The Mina2Configuration class has 78 lines of code with various options and logic, indicating that the method may be doing too many things and could be broken up into smaller, more focused methods. 3. Dead code: The getCharsetName() method contains an if statement which can never be true, as the encoding parameter can never be null. 4. Non-standard naming convention: The setSslContextParameters() method uses camel case instead of the standard Java naming convention of using lower camel case. 5. Commented-out code: The getUriString() method contains code that is commented out, which may indicate that it is no longer needed but was not removed. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | Feature envy: The Mina2Configuration class contains a lot of getters and setters for the various options, which shows that functionality is probably spread out among different classes2 Long method: The Mina2Configuration class has 78 lines of code with various options and logic, indicating that the method may be doing too many things and could be broken up into smaller, more focused methods3 Dead code: The getCharsetName() method contains an if statement which can never be true, as the encoding parameter can never be null4 Non-standard naming convention: The setSslContextParameters() method uses camel case instead of the standard Java naming convention of using lower camel case5 Commented-out code: The getUriString() method contains code that is commented out, which may indicate that it is no longer needed but was not removed | t | f | f | . Feature envy: The Mina2Configuration class contains a lot of getters and setters for the various options, which shows that functionality is probably spread out among different classes.2. Long method: The Mina2Configuration class has 78 lines of code with various options and logic, indicating that the method may be doing too many things and could be broken up into smaller, more focused methods.3. Dead code: The getCharsetName() method contains an if statement which can never be true, as the encoding parameter can never be null.4. Non-standard naming convention: The setSslContextParameters() method uses camel case instead of the standard Java naming convention of using lower camel case.5. Commented-out code: The getUriString() method contains code that is commented out, which may indicate that it is no longer needed but was not removed. | data class | 0 | 11643 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 1674 | 11643 |
| 1675 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | long method | t | t | t | 0 | 11644 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 1675 | 11644 | ||
| 1675 | YES I found bad smells the bad smells are: Duplicated code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | Duplicated code | t | f | f | Duplicated code | long method | 0 | 11644 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 1675 | 11644 |
| 1676 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 11645 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 1676 | 11645 |
| 1676 | YES I found bad smells the bad smells are: 1. Repetitive code 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
feature envy | Repetitive code2 Long method | t | f | f | . Repetitive code2. Long method | feature envy | 0 | 11645 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 1676 | 11645 |
| 1677 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | 1 Long Method | t | f | t | 0 | 11648 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 1677 | 11648 | ||
| 1677 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11648 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 1677 | 11648 | ||
| 1678 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | t | f | f | feature envy | 0 | 11649 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 1678 | 11649 | ||
| 1678 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11649 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 1678 | 11649 | ||
| 1679 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11653 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 1 | 1679 | 11653 | |
| 1679 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Duplicated code, 3. Conditional complexity, 4. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long method, 2 Duplicated code, 3 Conditional complexity, 4 Long parameter list | t | f | t | 2. Duplicated code, 3. Conditional complexity, 4. Long parameter list | 0 | 11653 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 2 | 1679 | 11653 | |
| 1680 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long Method | t | f | t | 0 | 11666 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 1680 | 11666 | ||
| 1680 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11666 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 1680 | 11666 | ||
| 1681 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11679 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 1 | 1681 | 11679 |
| 1681 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 11679 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 2 | 1681 | 11679 | ||
| 1682 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Data Class, Long Method | t | f | t | Data Class | 0 | 11682 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 1682 | 11682 | |
| 1682 | return HiveAlgorithmsUtil.getJoinCumulativeMemoryWithinPhaseSplit(join); YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method 2 Feature envy | t | f | t | 0 | 11682 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 1682 | 11682 | ||
| 1685 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11686 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 1685 | 11686 |
| 1687 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long Method | t | f | t | 0 | 11691 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 1 | 1687 | 11691 | ||
| 1687 | YES, I found bad smells: the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (specifically, the try/catch blocks for loading the comparator) 4. Inconsistent naming conventions (classLoadComparator instead of loadClassComparator) 5. Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException) 6. Use of multiple exit points (through the use of "throw" statements within the method) 7. Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes) 8. Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly) 9. Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) 10. Inadequate comments (lack of comments explaining the purpose and functionality of the code) 11. High cyclomatic complexity (multiple nested try/catch blocks and if statements) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long method 2 Feature envy3 Duplicate code (specifically, the try/catch blocks for loading the comparator)4 Inconsistent naming conventions (classLoadComparator instead of loadClassComparator)5 Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException)6 Use of multiple exit points (through the use of "throw" statements within the method)7 Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes)8 Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly)9 Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) | t | f | t | the try/catch blocks for loading the comparator)4. Inconsistent naming conventions (classLoadComparator instead of loadClassComparator)5. Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException)6. Use of multiple exit points (through the use of "throw" statements within the method)7. Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes)8. Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly)9. Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) | 0 | 11691 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 2 | 1687 | 11691 | |
| 1688 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent indentation 4. Magic numbers 5. Lack of meaningful variable names 6. Inappropriate or excessive use of comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method2 Feature envy3 Inconsistent indentation4 Magic numbers5 Lack of meaningful variable names6 Inappropriate or excessive use of comments | t | f | t | 0 | 11692 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 1688 | 11692 | ||
| 1688 | { "YES I found bad smells": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11692 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 1688 | 11692 | |
| 1692 | { "message": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | t | f | f | long method | 0 | 11712 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 1 | 1692 | 11712 | ||
| 1692 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional statements 5. Inappropriate exception handling 6. Poor naming conventions 7. Lack of modularity and encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Complex conditional statements 5 Inappropriate exception handling 6 Poor naming conventions 7 Lack of modularity and encapsulation | t | f | t | 0 | 11712 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 2 | 1692 | 11712 | ||
| 1693 | { "output": "YES I found bad smells", "detected_bad_smells": { "1": "Long Method", "2": "Blob" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | t | f | f | long method | 0 | 11716 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 1693 | 11716 | ||
| 1693 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11716 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 1693 | 11716 | ||
| 1694 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | 'Long Method' | t | t | t | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',L,o,n,g," ",M,h,o,d,'} | 0 | 11718 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1694 | 11718 |
| 1694 | YES I found bad smells, 1. Long method, 2. Complex conditional logic with multiple nested if statements, 3. Feature envy (internalFuture is accessed multiple times within the get() method), 4. Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5. Mixing of different levels of abstraction (usage of both explicit TimeUnit.MILLISECONDS and direct system millisecond calculations) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method, 2 Complex conditional logic with multiple nested if statements, 3 Feature envy (internalFuture is accessed multiple times within the get() method), 4 Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5 Mixing of different levels of abstraction (usage of both explicit TimeUnitMILLISECONDS and direct system millisecond calculations) | t | f | t | 2. Complex conditional logic with multiple nested if statements, 3. Feature envy (internalFuture is accessed multiple times within the get() method), 4. Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5. Mixing of different levels of abstraction (usage of both explicit TimeUnit.MILLISECONDS and direct system millisecond calculations) | 0 | 11718 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1694 | 11718 | |
| 1695 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 11719 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1695 | 11719 | |
| 1695 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Nested Synchronization, 4. Multiple exception types, 5. Hard coding, 6. Magic numbers, 7. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
feature envy | Long method, 2 Feature envy, 3 Nested Synchronization, 4 Multiple exception types, 5 Hard coding, 6 Magic numbers, 7 Code duplication | t | f | t | . Long method, 3. Nested Synchronization, 4. Multiple exception types, 5. Hard coding, 6. Magic numbers, 7. Code duplication. | 0 | 11719 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1695 | 11719 | |
| 1698 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | 1 Data Class | t | f | t | 0 | 11733 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 1 | 1698 | 11733 | ||
| 1698 | YES I found bad smells the bad smells are: Feature envy: 1. Long method 2. Unnecessary comments 3. Poorly named variables (filename, offset) 4. Redundant code in the constructor 5. Mixing of business logic and exception handling code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | Long method 2 Unnecessary comments 3 Poorly named variables (filename, offset) 4 Redundant code in the constructor 5 Mixing of business logic and exception handling code | t | f | f | . Long method 2. Unnecessary comments 3. Poorly named variables (filename, offset) 4. Redundant code in the constructor 5. Mixing of business logic and exception handling code | data class | 0 | 11733 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 2 | 1698 | 11733 |
| 1699 | { "message": "YES I found bad smells", "the bad smells are:": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 11734 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 1699 | 11734 |
| 1699 | {"response": "YES I found bad smells", "detected bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | data class | t | t | t | 0 | 11734 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 1699 | 11734 | ||
| 1701 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | long method, data class | t | t | t | long method | 0 | 11736 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 1701 | 11736 | |
| 1704 | public static class NotificationsService { private final NotificationsAggregatorState state;-------------- YES I found bad smells the bad smells are: 1. Undescriptive and unclear class names (NotificationsAggregatorState and NotificationsService) 2. Encapsulation violation (direct access to the state variable instead of using a getter) 3. Lack of modularity (actions and state are contained within a single class) 4. Lack of proper commenting/documentation 5. Violation of the single responsibility principle (class is performing too many tasks) 6. Violation of the open-closed principle (class is not easily extensible) 7. Lack of proper formatting and indentation 8. Unclear and inconsistent variable naming (recentEventLogsCount and activeRequestsCount) 9. Potential thread-unsafe access to variables (depending on the context and usage of the class) 10. Lack of exception handling 11. Potential code duplication (if similar functionality is implemented elsewhere) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | Undescriptive and unclear class names (NotificationsAggregatorState and NotificationsService) 2 Encapsulation violation (direct access to the state variable instead of using a getter) 3 Lack of modularity (actions and state are contained within a single class) 4 Lack of proper commenting/documentation 5 Violation of the single responsibility principle (class is performing too many tasks) 6 Violation of the open-closed principle (class is not easily extensible) 7 Lack of proper formatting and indentation 8 Unclear and inconsistent variable naming (recentEventLogsCount and activeRequestsCount) 9 Potential thread-unsafe access to variables (depending on the context and usage of the class) | t | f | f | . Undescriptive and unclear class names (NotificationsAggregatorState and NotificationsService) 2. Encapsulation violation (direct access to the state variable instead of using a getter) 3. Lack of modularity (actions and state are contained within a single class) 4. Lack of proper commenting/documentation 5. Violation of the single responsibility principle (class is performing too many tasks) 6. Violation of the open-closed principle (class is not easily extensible) 7. Lack of proper formatting and indentation 8. Unclear and inconsistent variable naming (recentEventLogsCount and activeRequestsCount) 9. Potential thread-unsafe access to variables (depending on the context and usage of the class) | data class | 0 | 11741 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 1704 | 11741 |
| 1704 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | t | f | f | data class | 0 | 11741 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 1704 | 11741 | ||
| 1706 | {"message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 11754 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 2 | 1706 | 11754 |
| 1706 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
data class | data class, long method | t | t | t | long method | 0 | 11754 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 1 | 1706 | 11754 | |
| 1710 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | 1, Long Method | t | f | t | 1 | 0 | 11765 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 1710 | 11765 | |
| 1710 | YES, I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11765 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 1710 | 11765 | |
| 1711 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11768 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 1711 | 11768 | |
| 1711 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 11768 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 1711 | 11768 |
| 1712 | {"output": "YES I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | t | f | f | data class | 0 | 11772 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1712 | 11772 | ||
| 1712 | YES I found bad smells The bad smells are: 1. Duplicated code (methods to get and set bytesWritten, recordsWritten, writeTime) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Duplicated code (methods to get and set bytesWritten, recordsWritten, writeTime) | t | f | f | . Duplicated code (methods to get and set bytesWritten, recordsWritten, writeTime) | data class | 0 | 11772 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1712 | 11772 |
| 1714 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Data Class | t | f | t | 0 | 11776 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 1714 | 11776 | ||
| 1714 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11776 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 1714 | 11776 |
| 1716 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long Method | t | f | t | 0 | 11781 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1716 | 11781 | ||
| 1716 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11781 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1716 | 11781 | ||
| 1718 | { "message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11785 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 1 | 1718 | 11785 | |
| 1718 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Class with too many responsibilities 5. Use of static methods and variables 6. Poor variable naming (ex. jmx_property_ids, SQLServerPropertyIds) 7. Violation of Single Responsibility Principle (SRP) 8. Possible data duplication with the use of multiple maps for resource metrics. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | Long method 2 Feature envy 3 Nested loops 4 Class with too many responsibilities 5 Use of static methods and variables 6 Poor variable naming (ex jmx_property_ids, SQLServerPropertyIds) 7 Violation of Single Responsibility Principle (SRP) 8 Possible data duplication with the use of multiple maps for resource metrics | t | f | f | . Long method 2. Feature envy 3. Nested loops 4. Class with too many responsibilities 5. Use of static methods and variables 6. Poor variable naming (ex. jmx_property_ids, SQLServerPropertyIds) 7. Violation of Single Responsibility Principle (SRP) 8. Possible data duplication with the use of multiple maps for resource metrics. | data class | 0 | 11785 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 2 | 1718 | 11785 |
| 1719 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long Method | t | f | t | 0 | 11792 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 1719 | 11792 | ||
| 1719 | YES I found bad smells the bad smells are: 1. Long method 2. Complex implementation 3. Overly nested conditional statements 4. Lack of proper commenting/documentation 5. Feature envy (multiple lines of code that should be in a separate object or method) 6. Use of magic numbers 7. Lack of proper error handling 8. Unnecessary use of system calls/arrays 9. Inefficient use of loops/iterations 10. Poor variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long method 2 Complex implementation 3 Overly nested conditional statements 4 Lack of proper commenting/documentation 5 Feature envy (multiple lines of code that should be in a separate object or method) 6 Use of magic numbers 7 Lack of proper error handling 8 Unnecessary use of system calls/arrays 9 Inefficient use of loops/iterations | t | f | t | 0 | 11792 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 1719 | 11792 | ||
| 1720 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | t | f | f | data class | 0 | 11795 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 1720 | 11795 | ||
| 1720 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11795 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 1720 | 11795 |
| 1724 | YES I found bad smells the bad smells are: 1. Missing documentation 2. Long method 3. Feature envy 4. Inefficient hashCode() and equals() methods 5. Poorly named variables (left, right) 6. Empty TODO comments 7. Class is not properly abstract as it contains some method implementations 8. Lack of proper encapsulation, as the setters are public and can be accessed directly instead of through methods. 9. Possible violation of coding conventions (method names should start with lowercase) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Missing documentation2 Long method3 Feature envy4 Inefficient hashCode() and equals() methods5 Poorly named variables (left, right)6 Empty TODO comments7 Class is not properly abstract as it contains some method implementations8 Lack of proper encapsulation, as the setters are public and can be accessed directly instead of through methods9 Possible violation of coding conventions (method names should start with lowercase) | t | f | f | . Missing documentation2. Long method3. Feature envy4. Inefficient hashCode() and equals() methods5. Poorly named variables (left, right)6. Empty TODO comments7. Class is not properly abstract as it contains some method implementations8. Lack of proper encapsulation, as the setters are public and can be accessed directly instead of through methods.9. Possible violation of coding conventions (method names should start with lowercase) | data class | 0 | 11803 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 1724 | 11803 |
| 1727 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | f | f | f | long method | 0 | 11810 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 1727 | 11810 | ||
| 1727 | private boolean isDSAPublicKeyWithoutParams(PublicKey key) { if (key.getAlgorithm().equals("DSA")) { try { key.getEncoded(); return false; } catch (NullPointerException npe) { return true; YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method2Feature envy | t | f | t | 0 | 11810 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 1727 | 11810 | ||
| 1728 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | f | f | f | feature envy | 0 | 11811 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 1728 | 11811 | ||
| 1728 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | t | f | f | feature envy | 0 | 11811 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 1728 | 11811 | ||
| 1730 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 11819 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 1 | 1730 | 11819 | |
| 1730 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 11819 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 2 | 1730 | 11819 |
| 1731 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 11820 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 1 | 1731 | 11820 |
| 1731 | YES, I found bad smells the bad smells are: 1.Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
feature envy | Long method, 2 Feature envy | t | f | t | .Long method | 0 | 11820 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 1731 | 11820 | |
| 1732 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | 1 Long Method | t | f | t | 0 | 11821 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 1 | 1732 | 11821 | ||
| 1732 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession 5. Duplicate code 6. Magic numbers (e.g. 32) 7. Poor naming (e.g. variables like "ent" and "iter") 8. Indicators of complex or confusing logic (e.g. multiple if statements checking for different conditions) 9. Comments left in the code (e.g. promise to remove println) 10. Use of non-descriptive or ambiguous variable names (e.g. "dst" or "src") 11. Lack of proper exception handling (e.g. if (ent.getType() == LogEntry.Type.TXN) throws an unchecked exception). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | Long method2 Feature envy 3 Data class4 Primitive obsession5 Duplicate code6 Magic numbers (eg 32)7 Poor naming (eg variables like "ent" and "iter")8 Indicators of complex or confusing logic (eg multiple if statements checking for different conditions)9 Comments left in the code (eg promise to remove println) | t | f | t | 0 | 11821 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 1732 | 11821 | ||
| 1733 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 11822 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1733 | 11822 | |
| 1733 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (the use of CellarSupport class multiple times within the method) 3. Lack of exception handling 4. Magic numbers (use of numbers without explanation within the code) 5. Poorly named variables (e.g. "in", "out", "pid", etc.) 6. Lack of comments/ documentation 7. Duplicated code 8. Inconsistent formatting (e.g. use of tabs and spaces) 9. Use of System.out.println statements for error handling 10. Mixing display mode and edit mode within the same method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | Long method2 Feature envy (the use of CellarSupport class multiple times within the method)3 Lack of exception handling 4 Magic numbers (use of numbers without explanation within the code)5 Poorly named variables (eg "in", "out", "pid", etc)6 Lack of comments/ documentation7 Duplicated code 8 Inconsistent formatting (eg use of tabs and spaces) 9 Use of Systemoutprintln statements for error handling | t | f | t | "out", "pid", etc.)6. Lack of comments/ documentation7. Duplicated code 8. Inconsistent formatting (e.g. use of tabs and spaces) 9. Use of System.out.println statements for error handling | 0 | 11822 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1733 | 11822 | |
| 1734 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long Method | t | f | t | 0 | 11823 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1734 | 11823 | ||
| 1734 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11823 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1734 | 11823 | ||
| 1736 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | t | f | f | data class | 0 | 11827 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 1 | 1736 | 11827 | ||
| 1736 | YES I found bad smells, the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11827 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 2 | 1736 | 11827 |
| 1737 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11831 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 1737 | 11831 | |
| 1737 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11831 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 1737 | 11831 | |
| 1739 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Long Method | t | f | t | 0 | 11836 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 1 | 1739 | 11836 | ||
| 1739 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code - the same code is repeated multiple times within the method. 4. Magic numbers - the values 1, 11, and 0 are used without explanation. 5. Poor naming - variable names such as "locales" and "slash" are vague and do not clearly explain their purpose or contents. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Feature envy2 Long method3 Duplicate code - the same code is repeated multiple times within the method 4 Magic numbers - the values | t | f | t | 0 | 11836 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 2 | 1739 | 11836 | ||
| 1742 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11845 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 1742 | 11845 |
| 1743 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Data Class | t | f | t | 0 | 11846 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 1 | 1743 | 11846 | ||
| 1743 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11846 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 2 | 1743 | 11846 |
| 1744 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long Method | t | f | t | 0 | 11849 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 1744 | 11849 | ||
| 1744 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Conditional complexity 5. Inconsistent naming convention 6. Confusing variable names 7. Lack of comments/documentation 8. Use of magic numbers or strings | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long method2 Feature envy3 Duplicated code4 Conditional complexity 5 Inconsistent naming convention 6 Confusing variable names 7 Lack of comments/documentation 8 Use of magic numbers or strings | t | f | t | 0 | 11849 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 1744 | 11849 | ||
| 1745 | { "message": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | long method | t | t | t | 0 | 11851 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 1 | 1745 | 11851 | ||
| 1745 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number (n > 0, index < n-1, index > 0) 3. Feature envy (container.getLength(), container.indexOf()) 4. Duplicated code (similar code blocks for FORWARD and BACKWARD cases) 5. Switch statement without a default case 6. Poor exception handling (throwing IllegalArgumentException instead of specific exceptions, ignoring other possible exceptions) 7. Lack of comments/documentation to explain the purpose of the method and its parameters/return value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | Long method 2 Magic number (n > 0, index < n- | t | f | t | index < n- | 0 | 11851 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 2 | 1745 | 11851 | |
| 1746 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11853 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 1746 | 11853 | |
| 1746 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11853 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 1746 | 11853 | ||
| 1747 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long Method | t | f | t | 0 | 11855 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1747 | 11855 | ||
| 1747 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11855 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1747 | 11855 | |
| 1749 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | f | f | f | data class | 0 | 11857 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 1749 | 11857 | ||
| 1750 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | t | f | f | data class | 0 | 11858 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 1 | 1750 | 11858 | ||
| 1750 | YES I found bad smells the bad smells are: 1. Feature envy 2. Data clumps | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | Feature envy2 Data clumps | t | f | f | . Feature envy2. Data clumps | data class | 0 | 11858 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 2 | 1750 | 11858 |
| 1753 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11865 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 1 | 1753 | 11865 | |
| 1753 | YES I found bad smells The bad smells are: 1.Long method 2.Magic numbers 3.Coupled design 4.Dead code 5.Inconsistent formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long method2Magic numbers3Coupled design4Dead code 5Inconsistent formatting | t | f | t | 0 | 11865 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 2 | 1753 | 11865 | ||
| 1754 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | 1. data class | t | t | t | 0 | 11867 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 1 | 1754 | 11867 | ||
| 1754 | YES I found bad smells the bad smells are: 1. Data class 2. Repeated code for getters and setters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | Data class2 Repeated code for getters and setters | t | f | t | 0 | 11867 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 2 | 1754 | 11867 | ||
| 1757 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | 'Data Class' | t | t | t | {',D,a,t,a," ",C,l,a,s,s,'} | {',D,a,a," ",C,l,a,s,s,'} | 0 | 11877 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 1 | 1757 | 11877 |
| 1757 | YES I found bad smells The bad smells are: 1. Many queries and named queries combined in one class, resulting in a high complexity and decreased readability. 2. The use of abbreviations for variable names, making the code less readable and hard to understand. 3. The use of getters and setters for almost every property, which can lead to feature envy and bloated classes. 4. The use of defaultString() in getters, indicating a possible problem with handling null values. 5. The use of CascadeType.ALL and CascadeType.REMOVE in many places, which could lead to potential issues with cascading behavior. 6. The use of the @Basic annotation for some properties, which suggests that the mapping could have been done differently and more explicitly. 7. The use of @JoinColumn with insertable and updatable flags set to true, suggesting that the entity might not be fully designed for the database it should be mapped to. 8. The entity class is quite large and contains many properties and relationships, indicating a possible violation of the Single Responsibility Principle. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | Many queries and named queries combined in one class, resulting in a high complexity and decreased readability2 The use of abbreviations for variable names, making the code less readable and hard to understand3 The use of getters and setters for almost every property, which can lead to feature envy and bloated classes4 The use of defaultString() in getters, indicating a possible problem with handling null values5 The use of CascadeTypeALL and CascadeTypeREMOVE in many places, which could lead to potential issues with cascading behavior6 The use of the @Basic annotation for some properties, which suggests that the mapping could have been done differently and more explicitly7 The use of @JoinColumn with insertable and updatable flags set to true, suggesting that the entity might not be fully designed for the database it should be mapped to8 The entity class is quite large and contains many properties and relationships, indicating a possible violation of the Single Responsibility Principle | t | f | f | . Many queries and named queries combined in one class, resulting in a high complexity and decreased readability.2. The use of abbreviations for variable names, making the code less readable and hard to understand.3. The use of getters and setters for almost every property, which can lead to feature envy and bloated classes.4. The use of defaultString() in getters, indicating a possible problem with handling null values.5. The use of CascadeType.ALL and CascadeType.REMOVE in many places, which could lead to potential issues with cascading behavior.6. The use of the @Basic annotation for some properties, which suggests that the mapping could have been done differently and more explicitly.7. The use of @JoinColumn with insertable and updatable flags set to true, suggesting that the entity might not be fully designed for the database it should be mapped to.8. The entity class is quite large and contains many properties and relationships, indicating a possible violation of the Single Responsibility Principle. | data class | 0 | 11877 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 1757 | 11877 |
| 1759 | {"message": "YES I found bad smells the bad smells are:", "bad smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | t | f | f | data class | 0 | 11885 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 1 | 1759 | 11885 | ||
| 1759 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | Long method | t | f | f | Long method | data class | 0 | 11885 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 2 | 1759 | 11885 |
| 1761 | { "output": "YES I found bad smells the bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | t | f | f | data class | 0 | 11891 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 1761 | 11891 | ||
| 1761 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11891 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 1761 | 11891 |
| 1763 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long Method | t | f | t | 0 | 11896 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 1763 | 11896 | ||
| 1763 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the for loop) 4. Confusing logic/naming (headerValue vs hdr) 5. Magic numbers (CONFIG_PREFIX_OPTIONAL + ".") 6. Nested loops 7. Use of isEmpty() instead of checking for size() == 0 8. Code comments indicating potential issues or bad practices 9. Poor exception handling (consistently throwing the same exception) 10. Possible violation of Single Responsibility Principle (SRP), as the method is responsible for multiple tasks. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long method2 Feature envy3 Duplicate code (in the for loop)4 Confusing logic/naming (headerValue vs hdr)5 Magic numbers (CONFIG_PREFIX_OPTIONAL + "")6 Nested loops7 Use of isEmpty() instead of checking for size() == 08 Code comments indicating potential issues or bad practices9 Poor exception handling (consistently throwing the same exception) | t | f | t | 0 | 11896 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 1763 | 11896 | ||
| 1765 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | Data Class | t | f | t | 0 | 11903 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 1 | 1765 | 11903 | ||
| 1765 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11903 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 2 | 1765 | 11903 |
| 1766 | { "output": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | Data Class | t | f | t | 0 | 11911 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 1 | 1766 | 11911 | ||
| 1766 | YES, I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11911 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 2 | 1766 | 11911 |
| 1768 | {"output": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | t | f | f | long method | 0 | 11914 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 1768 | 11914 | ||
| 1768 | "YES I found bad smells Bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Long parameter list 5. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method2 Repeated code3 Feature envy4 Long parameter list5 Primitive obsession | t | f | t | 0 | 11914 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 1768 | 11914 | ||
| 1769 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11918 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 1 | 1769 | 11918 | |
| 1769 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 11918 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 2 | 1769 | 11918 |
| 1771 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 11920 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 1 | 1771 | 11920 | |
| 1771 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 11920 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 2 | 1771 | 11920 |
| 1773 | { "message": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | data class | t | t | t | 0 | 11931 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 1 | 1773 | 11931 | ||
| 1773 | YES I found bad smells the bad smells are: 1. Long method, 2. Data class, 3. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | Long method, 2 Data class, 3 Inappropriate intimacy | t | f | t | . Long method, 3. Inappropriate intimacy | 0 | 11931 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 1773 | 11931 | |
| 1774 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | data class | t | t | t | 0 | 11932 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 1 | 1774 | 11932 | ||
| 1774 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11932 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 2 | 1774 | 11932 |
| 1776 | {"message": "YES I found bad smells the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 11956 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 1776 | 11956 |
| 1776 | YES I found bad smells the bad smells are: 1. Inconsistent formatting and indentation, 2. Lack of comments or description of code/variables, 3. Unnecessary import statements, 4. Long method, 5. Feature envy, 6. Redundancy/Elimination of repeated code, 7. Violation of the Single Responsibility Principle (SRP), 8. Unnecessary use of superfluous boolean variables, 9. Use of hard-coded values instead of constants. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | Inconsistent formatting and indentation, 2 Lack of comments or description of code/variables, 3 Unnecessary import statements, 4 Long method, 5 Feature envy, 6 Redundancy/Elimination of repeated code, 7 Violation of the Single Responsibility Principle (SRP), 8 Unnecessary use of superfluous boolean variables, 9 Use of hard-coded values instead of constants | t | f | f | . Inconsistent formatting and indentation, 2. Lack of comments or description of code/variables, 3. Unnecessary import statements, 4. Long method, 5. Feature envy, 6. Redundancy/Elimination of repeated code, 7. Violation of the Single Responsibility Principle (SRP), 8. Unnecessary use of superfluous boolean variables, 9. Use of hard-coded values instead of constants. | data class | 0 | 11956 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 1776 | 11956 |
| 1779 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Data class", "Message chain", "Data clumps", "Primitive obsession", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | long method, data class, message chain, data clumps, primitive obsession, feature envy | t | t | t | long method, message chain, data clumps, primitive obsession, feature envy | 0 | 11959 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 2 | 1779 | 11959 | |
| 1781 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | t | f | f | long method | 0 | 11962 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 1 | 1781 | 11962 | ||
| 1781 | YES I found bad smells the bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | Long method, Feature envy | t | f | t | Feature envy. | 0 | 11962 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 2 | 1781 | 11962 | |
| 1785 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long Method | t | f | t | 0 | 11978 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 1785 | 11978 | ||
| 1785 | YES I found bad smells: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11978 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 1785 | 11978 | ||
| 1786 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
feature envy | Long Method | t | f | f | Long Method | feature envy | 0 | 11979 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 1786 | 11979 |
| 1786 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11979 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 1786 | 11979 | ||
| 1787 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | t | f | f | long method | 0 | 11981 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 1787 | 11981 | ||
| 1787 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11981 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 1787 | 11981 | ||
| 1789 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | t | f | f | long method | 0 | 11985 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 1 | 1789 | 11985 | ||
| 1789 | YES, I found bad smells. The bad smells are: 1. Long method 2. Unnecessary complexity 3. Feature envy 4. Code duplication 5. Inappropriate coupling 6. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | Long method2 Unnecessary complexity3 Feature envy4 Code duplication5 Inappropriate coupling6 Incomplete error handling | t | f | t | 0 | 11985 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 2 | 1789 | 11985 | ||
| 1790 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | 'Long Method', 'Feature Envy' | t | t | t | {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',F,e,a,t,u,r,e," ",E,n,v,y,'} | {',L,o,n,g," ",M,h,o,d,',","," ",',F,a," ",n,v,y,'} | 0 | 11987 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 1790 | 11987 |
| 1790 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method2 Duplicate code | t | f | t | 0 | 11987 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 1790 | 11987 | ||
| 1791 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11988 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 1791 | 11988 |
| 1793 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11996 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 1793 | 11996 | |
| 1793 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11996 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 1793 | 11996 |
| 1795 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | 'Long Method' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',o,n,g," ",M,t,h,o,d,'} | 0 | 11998 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1795 | 11998 |
| 1795 | YES I found bad smells. The bad smells are: 1. Long method, 2. Duplicate code, 3. Magic numbers, 4. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | Long method, 2 Duplicate code, 3 Magic numbers, 4 Shotgun surgery | t | f | f | . Long method, 2. Duplicate code, 3. Magic numbers, 4. Shotgun surgery | feature envy | 0 | 11998 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1795 | 11998 |
| 1796 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 11999 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1796 | 11999 | ||
| 1796 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11999 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1796 | 11999 | ||
| 1797 | {"message":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method | t | t | t | 0 | 12001 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 1797 | 12001 | ||
| 1797 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12001 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 1797 | 12001 | ||
| 1799 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12009 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1799 | 12009 |
| 1799 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Inappropriate naming/low readability 4. Use of exception handling for control flow 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | Long method2 Duplicate code3 Inappropriate naming/low readability4 Use of exception handling for control flow5 Feature envy | t | f | t | 0 | 12009 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1799 | 12009 | ||
| 1800 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long Method | t | f | t | 0 | 12011 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 1800 | 12011 | ||
| 1800 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Inconsistent indentations 4. Magic numbers 5. Nested if statements 6. Complex boolean expressions 7. Hard-to-understand variable names 8. Unused variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method 2 Duplicate code 3 Inconsistent indentations 4 Magic numbers 5 Nested if statements 6 Complex boolean expressions 7 Hard-to-understand variable names 8 Unused variables | t | f | t | 0 | 12011 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 1800 | 12011 | ||
| 1803 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | t | f | f | data class | 0 | 12021 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 1803 | 12021 | ||
| 1803 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Inappropriate naming 5. Inconsistent formatting and spacing 6. Deeply nested structure 7. Unused code 8. Code duplication 9. Non-optimized imports 10. Comments that are not helpful or redundant 11. Poor exception handling 12. Misplaced responsibilities 13. Overuse of static methods and variables 14. Insufficient encapsulation 15. Inconsistent use of modifiers 16. Lack of proper logging statements 17. Lack of validation for input parameters 18. Poor naming conventions for variables and methods 19. Excessive depth of inheritance hierarchy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | Long method2 Feature envy3 Data class4 Inappropriate naming5 Inconsistent formatting and spacing6 Deeply nested structure7 Unused code8 Code duplication9 Non-optimized imports | t | f | t | 0 | 12021 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 1803 | 12021 | ||
| 1806 | {"message": "YES I found bad smells", "bad_smells": [ "Data Class" ]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Data Class | t | f | t | 0 | 12041 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 1 | 1806 | 12041 | ||
| 1806 | YES I found bad smellsthe bad smells are:- 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 12041 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 2 | 1806 | 12041 |
| 1808 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 12049 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 1 | 1808 | 12049 | |
| 1808 | YES I found bad smells. the bad smells are: 1. Feature envy: The jsonString() method uses a utility class (JsonUtils) to perform its logic, indicating that it may be better suited as a member of that class rather than in the User class. 2. Primitive obsession: The User class uses primitive types (String, int) instead of creating custom objects that encapsulate the data. 3. Long parameter list: The constructor for the User class does not have a default empty constructor, and its only constructor has multiple parameters, which may cause maintenance issues as more data needs to be added in the future. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | Feature envy: The jsonString() method uses a utility class (JsonUtils) to perform its logic, indicating that it may be better suited as a member of that class rather than in the User class2 Primitive obsession: The User class uses primitive types (String, int) instead of creating custom objects that encapsulate the data3 Long parameter list: The constructor for the User class does not have a default empty constructor, and its only constructor has multiple parameters, which may cause maintenance issues as more data needs to be added in the future | t | f | f | . Feature envy: The jsonString() method uses a utility class (JsonUtils) to perform its logic, indicating that it may be better suited as a member of that class rather than in the User class.2. Primitive obsession: The User class uses primitive types (String, int) instead of creating custom objects that encapsulate the data.3. Long parameter list: The constructor for the User class does not have a default empty constructor, and its only constructor has multiple parameters, which may cause maintenance issues as more data needs to be added in the future. | data class | 0 | 12049 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 2 | 1808 | 12049 |
| 1809 | {"message": "YES, I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | t | f | f | long method | 0 | 12052 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 1809 | 12052 | ||
| 1809 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12052 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 1809 | 12052 | |
| 1810 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long Method | t | f | t | 0 | 12056 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 1810 | 12056 | ||
| 1810 | YES, I found bad smells, the bad smells are: 1. Long method 2. Repetitive code for removing double underscores 3. Excessive use of nested loops 4. Feature envy (the method is performing operations that should be done by another object) 5. Magic numbers without explanatory comments 6. Poor naming conventions (i, usIndex) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Repetitive code for removing double underscores3 Excessive use of nested loops4 Feature envy (the method is performing operations that should be done by another object)5 Magic numbers without explanatory comments6 Poor naming conventions (i, usIndex) | t | f | t | usIndex) | 0 | 12056 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 1810 | 12056 | |
| 1811 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Data Class | t | f | t | 0 | 12061 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 1 | 1811 | 12061 | ||
| 1811 | YES I found bad smells The bad smells are: 1. Deprecated class without further explanation 2. Two getter and setter methods 3. No clear purpose or functionality of the class 4. Naming inconsistency (offset vs producerGroup) 5. Lack of encapsulation as variables are directly accessible without methods for validation or control. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Deprecated class without further explanation2 Two getter and setter methods 3 No clear purpose or functionality of the class4 Naming inconsistency (offset vs producerGroup) 5 Lack of encapsulation as variables are directly accessible without methods for validation or control | t | f | f | . Deprecated class without further explanation2. Two getter and setter methods 3. No clear purpose or functionality of the class4. Naming inconsistency (offset vs producerGroup) 5. Lack of encapsulation as variables are directly accessible without methods for validation or control. | data class | 0 | 12061 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 2 | 1811 | 12061 |
| 1812 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 12063 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 1 | 1812 | 12063 | |
| 1812 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12063 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 2 | 1812 | 12063 |
| 1814 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 12067 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 1814 | 12067 | |
| 1814 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12067 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 1814 | 12067 |
| 1817 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 12088 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1817 | 12088 | |
| 1817 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Temporary fields 4. Duplicate code 5. Catch-all exception handling 6. Resource cleanup issues (closing sentryClient in finally block instead of using try-with-resources) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy3 Temporary fields4 Duplicate code5 Catch-all exception handling6 Resource cleanup issues (closing sentryClient in finally block instead of using try-with-resources) | t | f | t | 0 | 12088 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1817 | 12088 | ||
| 1818 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 12089 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1818 | 12089 | |
| 1818 | "YES I found bad smells" the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Magic numbers/strings 5. Catching general exceptions 6. Duplicated code 7. Poor error handling 8. Complex conditional logic 9. Unused or unnecessary variables 10. Hard-to-read variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Long method2 Feature envy3 Nested loops4 Magic numbers/strings5 Catching general exceptions6 Duplicated code7 Poor error handling8 Complex conditional logic9 Unused or unnecessary variables | t | f | t | 0 | 12089 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1818 | 12089 | ||
| 1825 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 12107 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 2 | 1825 | 12107 | ||
| 1825 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 12107 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 1 | 1825 | 12107 | ||
| 1826 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12112 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 1826 | 12112 | |
| 1826 | YES I found bad smells the bad smells are: 1.Long method 2.Magic number 3.Duplicate code 4.Message chains 5.Data class 6.Inappropriate intimacy 7.Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method 2Magic number 3Duplicate code 4Message chains 5Data class 6Inappropriate intimacy7Shotgun surgery | t | f | t | 0 | 12112 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 1826 | 12112 | ||
| 1829 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 12118 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 1829 | 12118 | |
| 1829 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12118 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 1829 | 12118 | ||
| 1830 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method | t | t | t | 0 | 12121 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 1830 | 12121 | ||
| 1830 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12121 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 1830 | 12121 | ||
| 1831 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12126 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 2 | 1831 | 12126 |
| 1832 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 12128 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 1 | 1832 | 12128 | |
| 1832 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Lack of comments/documentation 5. Inappropriate naming conventions (e.g. variables named with abbreviations) 6. Nested if-else statements 7. Redundant code 8. Lack of error handling 9. Code duplication 10. Lack of encapsulation/modularity 11. Non-descriptive naming conventions 12. Not following best coding practices (e.g. using Thread.sleep() instead of ScheduledExecutorService) 13. Using a semaphore as a means of loop control 14. Lack of meaningful separation of concerns (e.g. mixing job execution logic with metrics/logging) 15. Inconsistent use of logger (e.g. sometimes using logger.debug() and other times using logger.error() for the same information) 16. Unnecessary use of try-catch blocks | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
data class | Long method2 Feature envy3 Magic numbers4 Lack of comments/documentation5 Inappropriate naming conventions (eg variables named with abbreviations)6 Nested if-else statements7 Redundant code8 Lack of error handling9 Code duplication | t | f | f | . Long method2. Feature envy3. Magic numbers4. Lack of comments/documentation5. Inappropriate naming conventions (e.g. variables named with abbreviations)6. Nested if-else statements7. Redundant code8. Lack of error handling9. Code duplication | data class | 0 | 12128 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 2 | 1832 | 12128 |
| 1834 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | t | f | f | long method | 0 | 12132 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 1834 | 12132 | ||
| 1834 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12132 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 1834 | 12132 | ||
| 1835 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 12133 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 1835 | 12133 | |
| 1835 | YES I found bad smells The bad smells are: 1. Long method 2. Type Checking 3. Temporal coupling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
feature envy | Long method2 Type Checking3 Temporal coupling | t | f | f | . Long method2. Type Checking3. Temporal coupling | feature envy | 0 | 12133 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 1835 | 12133 |
| 1836 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long Method | t | f | t | 0 | 12140 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 1 | 1836 | 12140 | ||
| 1836 | YES I found bad smells The bad smells are: Long method, Inappropriate naming, Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long method, Inappropriate naming, Duplicate code | t | f | t | Inappropriate naming, Duplicate code | 0 | 12140 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 2 | 1836 | 12140 | |
| 1837 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12142 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 1837 | 12142 | |
| 1837 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: the NormalizeResutlSetNode class is accessing methods and data from other classes, including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code. 3. Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers. 4. Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code. 5. Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method. 6. Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring. 7. Code duplication: some lines of code, such as "chldRes.getResultColumns()", are duplicated in different parts of the code, indicating code duplication. 8. Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand. 9. Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
long method | Long method2 Feature envy: the NormalizeResutlSetNode class is accessing methods and data from other classes, including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code3 Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers4 Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code5 Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method6 Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring7 Code duplication: some lines of code, such as "chldResgetResultColumns()", are duplicated in different parts of the code, indicating code duplication8 Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand9 Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation | t | f | t | including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code.3. Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers.4. Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code.5. Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method.6. Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring.7. Code duplication: some lines of code, such as "chldRes.getResultColumns()", are duplicated in different parts of the code, indicating code duplication.8. Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand.9. Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation. | 0 | 12142 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 1837 | 12142 | |
| 1838 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 12143 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 1838 | 12143 |
| 1838 | YES I found bad smells the bad smells are: - Long method - Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | - Long method- Feature envy | t | f | t | 0 | 12143 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 1838 | 12143 | ||
| 1840 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | t | f | f | long method | 0 | 12149 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 1840 | 12149 | ||
| 1840 | YES I found bad smells: 1. Long method, 2. Magic number, 3. Feature envy, 4. Duplicate code: LOG.info statements, 5. Redundant code: null check for dirRoot, 6. Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7. Lack of clear separation of concerns: mixing of logging and crawling functionality, 8. Lack of proper error handling and exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | Long method, 2 Magic number, 3 Feature envy, 4 Duplicate code: LOGinfo statements, 5 Redundant code: null check for dirRoot, 6 Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7 Lack of clear separation of concerns: mixing of logging and crawling functionality, 8 Lack of proper error handling and exception handling | t | f | t | 2. Magic number, 3. Feature envy, 4. Duplicate code: LOG.info statements, 5. Redundant code: null check for dirRoot, 6. Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7. Lack of clear separation of concerns: mixing of logging and crawling functionality, 8. Lack of proper error handling and exception handling. | 0 | 12149 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 1840 | 12149 | |
| 1841 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 12150 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 1841 | 12150 |
| 1841 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 12150 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 1841 | 12150 | ||
| 1842 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | 1, Long Method | t | f | t | 1 | 0 | 12151 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 1842 | 12151 | |
| 1842 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12151 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 1842 | 12151 | ||
| 1845 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12164 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 1845 | 12164 | |
| 1845 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Indecent Exposure, 4. Drill-down, 5. Inappropriate Intimacy, 6. Temporary Field, 7. Large Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method, 2 Feature envy, 3 Indecent Exposure, 4 Drill-down, 5 Inappropriate Intimacy, 6 Temporary Field, 7 Large Class | t | f | t | 2. Feature envy, 3. Indecent Exposure, 4. Drill-down, 5. Inappropriate Intimacy, 6. Temporary Field, 7. Large Class | 0 | 12164 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 1845 | 12164 | |
| 1847 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | t | f | f | long method | 0 | 12172 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 1847 | 12172 | ||
| 1847 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12172 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 1847 | 12172 | ||
| 1848 | {"output":"YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12186 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 1 | 1848 | 12186 |
| 1848 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 12186 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 2 | 1848 | 12186 |
| 1851 | { "output": "YES I found bad smells", "the bad smells are:": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | t | f | f | data class | 0 | 12190 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 1851 | 12190 | ||
| 1851 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy: multiple methods operate on the same instance variables 3. Primitive obsession: use of multiple boolean variables to represent different types 4. Message chain: method chaining in multiple places 5. Data class: class contains no behavior and just stores data 6. Duplicated code: similar logic repeated in multiple methods 7. Lack of encapsulation: direct access to all instance variables from outside the class 8. Switch statements instead of polymorphism: if/else statements used to handle different types instead of creating subclasses 9. Lack of abstraction: many specific boolean variables used instead of a single abstracted class 10. Comments used instead of meaningful method names: non-descriptive method names with comments explaining functionality instead 11. Unnecessary constructor parameters: excessive parameters in constructor that are not used in the class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Long method2 Feature envy: multiple methods operate on the same instance variables 3 Primitive obsession: use of multiple boolean variables to represent different types 4 Message chain: method chaining in multiple places 5 Data class: class contains no behavior and just stores data 6 Duplicated code: similar logic repeated in multiple methods 7 Lack of encapsulation: direct access to all instance variables from outside the class 8 Switch statements instead of polymorphism: if/else statements used to handle different types instead of creating subclasses 9 Lack of abstraction: many specific boolean variables used instead of a single abstracted class | t | f | t | 0 | 12190 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 1851 | 12190 | ||
| 1854 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
data class | long method, data class | t | t | t | long method | 0 | 12206 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 1 | 1854 | 12206 | |
| 1854 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12206 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 2 | 1854 | 12206 |
| 1857 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | long method | t | t | f | long method | data class | 0 | 12216 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 1857 | 12216 |
| 1857 | YES I found bad smells the bad smells are: 1. Unnecessary comments 2. Duplicate code 3. Serialization of a class that doesn't implement Serializable 4. Poor naming conventions for variables and methods (e.g. "keys" and "nextMarker" are not descriptive) 5. Inconsistent use of return values in setters (some methods return a reference to the object and others do not) 6. Large method with multiple responsibilities 7. Feature envy (e.g. withKeys() method accesses a private variable and also has responsibility for setting it) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | Unnecessary comments2 Duplicate code3 Serialization of a class that doesn't implement Serializable4 Poor naming conventions for variables and methods (eg "keys" and "nextMarker" are not descriptive)5 Inconsistent use of return values in setters (some methods return a reference to the object and others do not)6 Large method with multiple responsibilities 7 Feature envy (eg withKeys() method accesses a private variable and also has responsibility for setting it) | t | f | f | . Unnecessary comments2. Duplicate code3. Serialization of a class that doesn't implement Serializable4. Poor naming conventions for variables and methods (e.g. "keys" and "nextMarker" are not descriptive)5. Inconsistent use of return values in setters (some methods return a reference to the object and others do not)6. Large method with multiple responsibilities 7. Feature envy (e.g. withKeys() method accesses a private variable and also has responsibility for setting it) | data class | 0 | 12216 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 1857 | 12216 |
| 1859 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | long method | t | t | t | 0 | 12219 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1859 | 12219 | ||
| 1859 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent formatting 4. Resource leak - the code is not properly handling and closing resources such as files or connections 5. Potential NullPointerException in line 36 6. Magic numbers - hardcoded values in the code that are not properly explained or documented 7. Possible duplicate code 8. Overcomplicated code - the use of reflection to set caller context could be simplified 9. Lack of exception handling or error checking 10. Possible poor naming of variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Long method2 Feature envy3 Inconsistent formatting 4 Resource leak - the code is not properly handling and closing resources such as files or connections 5 Potential NullPointerException in line 36 6 Magic numbers - hardcoded values in the code that are not properly explained or documented 7 Possible duplicate code 8 Overcomplicated code - the use of reflection to set caller context could be simplified 9 Lack of exception handling or error checking | t | f | t | 0 | 12219 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1859 | 12219 | ||
| 1860 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | 1. long method | t | t | t | 0 | 12221 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 1860 | 12221 | ||
| 1860 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 12221 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 1860 | 12221 | ||
| 1861 | { "output": "YES, I did find bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method | t | t | t | 0 | 12222 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 1861 | 12222 | ||
| 1861 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12222 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 1861 | 12222 | ||
| 1864 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | long method | t | t | f | long method | data class | 0 | 12232 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 2 | 1864 | 12232 |
| 1866 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | data class, long method | t | t | t | long method | 0 | 12238 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 1 | 1866 | 12238 | |
| 1866 | YES I found bad smells the bad smells are: 1. Long class 2. Magic number (binary = false, charset = "UTF-8", dir = "/tmp/xd/output/", suffix = "out") 3. Feature envy (getName(), setName(), getDirExpression(), setDirExpression()) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long class2 Magic number (binary = false, charset = "UTF-8", dir = "/tmp/xd/output/", suffix = "out")3 Feature envy (getName(), setName(), getDirExpression(), setDirExpression()) | t | f | f | . Long class2. Magic number (binary = false, charset = "UTF-8", dir = "/tmp/xd/output/", suffix = "out")3. Feature envy (getName(), setName(), getDirExpression(), setDirExpression()) | data class | 0 | 12238 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 1866 | 12238 |
| 1869 | {"output":{"message":"YES I found bad smells","bad smells":["Blob","Long Method","Data Class"]}} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | {"message" | t | f | f | {"message" | data class | 0 | 12245 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 1869 | 12245 |
| 1869 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 12245 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 2 | 1869 | 12245 |
| 1871 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12249 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 1 | 1871 | 12249 |
| 1871 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12249 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 2 | 1871 | 12249 |
| 1875 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12262 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1875 | 12262 | |
| 1875 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12262 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1875 | 12262 | ||
| 1877 | { "message": "YES I found bad smells, the bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 12265 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 1877 | 12265 |
| 1877 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12265 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 1877 | 12265 |
| 1878 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | long method | t | t | t | 0 | 12273 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 1 | 1878 | 12273 | ||
| 1878 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12273 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 2 | 1878 | 12273 | ||
| 1880 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12284 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 1880 | 12284 | |
| 1880 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | f | f | f | long method | 0 | 12284 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 1880 | 12284 | ||
| 1881 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
long method | long method | t | t | t | 0 | 12286 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 1 | 1881 | 12286 | ||
| 1881 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12286 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 2 | 1881 | 12286 | ||
| 1882 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | long method | t | t | t | 0 | 12288 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 1882 | 12288 | ||
| 1882 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12288 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 1882 | 12288 | ||
| 1883 | { "message": "YES I found bad smells", "bad smells are": [ "6. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | 6. long method | t | t | f | 6. long method | feature envy | 0 | 12289 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 1883 | 12289 |
| 1883 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12289 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 1883 | 12289 | ||
| 1884 | { "output": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12292 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 1884 | 12292 |
| 1884 | YES I found bad smells The bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | Long method2 Feature Envy | t | f | t | 0 | 12292 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 1884 | 12292 | ||
| 1885 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent formatting and whitespace (inconsistent use of tabs/spaces) 4. Mixing of logging and exception handling in same method 5. Catching generic Exception class instead of specific exceptions 6. Use of instanceof operator 7. Nested, complex logic 8. Lack of proper error handling and messaging 9. Code duplication 10. Poor variable naming 11. Unnecessary use of Hashmap and casting 12. Unused variables 13. Inefficient use of EntityManager 14. Nested try-catch blocks 15. Inconsistent use of brackets/indentation 16. Fragile code (e.g. using string literals instead of constants) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method 2 Feature envy3 Inconsistent formatting and whitespace (inconsistent use of tabs/spaces)4 Mixing of logging and exception handling in same method5 Catching generic Exception class instead of specific exceptions6 Use of instanceof operator7 Nested, complex logic 8 Lack of proper error handling and messaging9 Code duplication | t | f | t | complex logic 8. Lack of proper error handling and messaging9. Code duplication | 0 | 12293 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 1885 | 12293 | |
| 1887 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12299 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 2 | 1887 | 12299 | ||
| 1891 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method | t | t | t | 0 | 12314 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 1 | 1891 | 12314 | ||
| 1891 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers (such as 0.0f, 1.0f) 3. Duplicate code within if statements (within if statement for align variable) 4. Single letter variable names (such as v, n) 5. Complex conditionals within if statements (such as align == 0.0f, align == 1.0f) 6. Inconsistent indentation 7. Use of float instead of double for mathematical operations 8. Lack of comments/documentation explaining the purpose of code or variables 9. Lack of error handling 10. Method performing multiple tasks (calculation and setting of variables) 11. Lack of encapsulation (variables and methods are protected instead of private) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | Long method2 Magic numbers (such as 00f, | t | f | t | 0 | 12314 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 2 | 1891 | 12314 | ||
| 1892 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method | t | t | t | 0 | 12318 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 1892 | 12318 | ||
| 1892 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic Number, 3.Duplicated code, 4.Data clumps, 5.Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method, 2Magic Number, 3Duplicated code, 4Data clumps, 5Conditional complexity | t | f | t | 2.Magic Number, 3.Duplicated code, 4.Data clumps, 5.Conditional complexity | 0 | 12318 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 1892 | 12318 | |
| 1893 | //(=> //{BinaryLogicalExpression.lhs=current} public Group getGroup_1_0_0() { return cGroup_1_0_0; } YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | _0_0() { return cGroup_ | t | f | f | _0_0() { return cGroup_ | data class | 0 | 12320 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 1893 | 12320 |
| 1893 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | long method, data class | t | t | t | long method | 0 | 12320 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 1893 | 12320 | |
| 1896 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | data class | t | t | t | 0 | 12334 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 1 | 1896 | 12334 | ||
| 1896 | YES I found bad smells 1. Long method, 2. Feature envy: the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | Long method, 2 Feature envy:the bad smells are: | t | f | f | . Long method, 2. Feature envy:the bad smells are: | data class | 0 | 12334 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 2 | 1896 | 12334 |
| 1897 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | long method | t | t | t | 0 | 12341 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 1 | 1897 | 12341 | ||
| 1897 | "Yes, I found bad smells. The bad smells are: Feature envy, long method." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | Feature envy, long method" | t | f | t | Feature envy | 0 | 12341 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 2 | 1897 | 12341 | |
| 1898 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | \n1. long method | t | t | t | 0 | 12351 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 1898 | 12351 | ||
| 1898 | YES found bad smells Amongst the bad smells found are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12351 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 1898 | 12351 | ||
| 1899 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | 1. long method | t | t | t | 0 | 12355 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 1899 | 12355 | ||
| 1899 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12355 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 1899 | 12355 | ||
| 1901 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 12362 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 1 | 1901 | 12362 |
| 1901 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12362 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 2 | 1901 | 12362 | ||
| 1902 | {"message": "YES I found bad smells", "bad smells are": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | 2. data class | t | t | f | data class | 0 | 12364 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 1902 | 12364 | |
| 1902 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12364 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 1902 | 12364 |
| 1905 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | data class | t | t | t | 0 | 12371 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 1 | 1905 | 12371 | ||
| 1905 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12371 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 2 | 1905 | 12371 |
| 1906 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | long method | t | t | t | 0 | 12380 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 1906 | 12380 | ||
| 1906 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Duplicate code 4. Conditional complexity 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long method2 Long parameter list3 Duplicate code4 Conditional complexity5 Feature envy | t | f | t | 0 | 12380 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 1906 | 12380 | ||
| 1909 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 1909 | 12397 |
| 1912 | { YES I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 12401 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 1912 | 12401 |
| 1913 | { "response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 12402 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 1913 | 12402 | |
| 1913 | YES, I found bad smells The bad smells are: long method, switch statements, feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method, switch statements, feature envy | t | f | t | switch statements, feature envy | 0 | 12402 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 1913 | 12402 | |
| 1914 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 12403 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 1914 | 12403 |
| 1914 | YES I found bad smells The bad smells are: 1.Long method 2.Duplicated code 3.Conditional complexity 4.Inappropriate naming 5.Magic number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
feature envy | Long method2Duplicated code3Conditional complexity4Inappropriate naming5Magic number | t | f | f | .Long method2.Duplicated code3.Conditional complexity4.Inappropriate naming5.Magic number | feature envy | 0 | 12403 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 1914 | 12403 |
| 1916 | {"message": "YES I found bad smells the bad smells are:", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | data class, long method | t | t | t | long method | 0 | 12408 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 1916 | 12408 | |
| 1916 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12408 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 1916 | 12408 |
| 1919 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | data class | t | t | t | 0 | 12412 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 1 | 1919 | 12412 | ||
| 1919 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12412 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1919 | 12412 |
| 1922 | JSE I found bad smells: 1. Long method 2. Feature envy 3. Data class 4. Indecent exposure 5. Complexity 6. Shotgun surgery 7. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | Long method2 Feature envy3 Data class4 Indecent exposure5 Complexity6 Shotgun surgery7 Inappropriate Intimacy | f | f | t | 0 | 12425 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 1922 | 12425 | ||
| 1922 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | data class | t | t | t | 0 | 12425 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 1922 | 12425 | ||
| 1923 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | long method | t | t | t | 0 | 12426 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 1 | 1923 | 12426 | ||
| 1923 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12426 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 2 | 1923 | 12426 | ||
| 1925 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 12434 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1925 | 12434 | ||
| 1925 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (repeated try-catch block) 4. Conditional complexity (multiple if/else statements) 5. Inconsistent naming conventions (some variables use camel case, others use underscores) 6. Poor exception handling (all exceptions are caught and logged, but no further action is taken) 7. Magic numbers used for calculations (e.g. division by 100f) 8. Nested conditionals (if/else within another if/else) 9. Inefficient use of memory (converting integers to floats for calculations) 10. Comments indicating potential issues that need to be fixed (indicates unmaintainable code) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Long method2 Feature envy3 Duplicate code (repeated try-catch block)4 Conditional complexity (multiple if/else statements)5 Inconsistent naming conventions (some variables use camel case, others use underscores)6 Poor exception handling (all exceptions are caught and logged, but no further action is taken)7 Magic numbers used for calculations (eg division by | t | f | t | others use underscores)6. Poor exception handling (all exceptions are caught and logged, but no further action is taken)7. Magic numbers used for calculations (e.g. division by | 0 | 12434 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1925 | 12434 | |
| 1926 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | long method | t | t | t | 0 | 12438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1926 | 12438 | ||
| 1926 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1926 | 12438 | ||
| 1927 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 12439 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1927 | 12439 |
| 1927 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Inappropriate commenting 4. Strong dependency (the method relies on the state of external variables) 5. Potential concurrency issues due to locking and unlocking of the sync mode | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
feature envy | Long method2 Feature envy3 Inappropriate commenting4 Strong dependency (the method relies on the state of external variables)5 Potential concurrency issues due to locking and unlocking of the sync mode | t | f | t | 0 | 12439 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1927 | 12439 | ||
| 1928 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 12445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 1928 | 12445 | ||
| 1930 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12453 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 1 | 1930 | 12453 |
| 1930 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12453 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 1930 | 12453 |
| 1931 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | long method | t | t | t | 0 | 12454 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1931 | 12454 | ||
| 1931 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12454 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1931 | 12454 | ||
| 1933 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | long method | t | t | t | 0 | 12457 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 1933 | 12457 | ||
| 1933 | YES I found bad smells the bad smells are: 1.Long method, 2. Feature envy, 3. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | Long method, 2 Feature envy, 3 Code duplication | t | f | t | 2. Feature envy, 3. Code duplication. | 0 | 12457 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 1933 | 12457 | |
| 1934 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | long method | t | t | t | 0 | 12462 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 1934 | 12462 | ||
| 1934 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | Long method | t | f | t | 0 | 12462 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 1934 | 12462 | ||
| 1941 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | 1. data class | t | t | f | data class | 0 | 12485 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 1941 | 12485 | |
| 1941 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12485 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 1941 | 12485 |
| 1942 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method, data class | t | t | t | data class | 0 | 12499 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1942 | 12499 | |
| 1942 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12499 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1942 | 12499 | ||
| 1943 | {"response": "YES, I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | data class | t | t | t | 0 | 12503 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 1 | 1943 | 12503 | ||
| 1943 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12503 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 2 | 1943 | 12503 |
| 1945 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Not specified | f | f | f | false | 0 | 12515 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 1945 | 12515 | |
| 1945 | YES I found bad smells The bad smells are: 1. Long method, 2. Data clumps, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method, 2 Data clumps, 3 Feature envy | t | f | t | 2. Data clumps, 3. Feature envy | 0 | 12515 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 1945 | 12515 | |
| 1947 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | 1. long method | t | t | f | long method | 0 | 12523 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 1947 | 12523 | |
| 1947 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12523 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 1947 | 12523 | ||
| 1950 | "YES I found bad smells" the bad smells are: 1. Poor variable and method naming conventions 2. No clear purpose or functionality for the class 3. Inconsistent use of constructor for both setting and getting ID and name 4. Excessive and repetitive code for setting and getting ID and name variables 5. No comments or documentation for the class or methods 6. No error handling for setting invalid values for ID or name 7. Possible feature envy for the Book class as it only contains getters and setters for two variables, but it is not clear what its purpose is or if it has any additional functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Poor variable and method naming conventions2 No clear purpose or functionality for the class3 Inconsistent use of constructor for both setting and getting ID and name 4 Excessive and repetitive code for setting and getting ID and name variables5 No comments or documentation for the class or methods6 No error handling for setting invalid values for ID or name7 Possible feature envy for the Book class as it only contains getters and setters for two variables, but it is not clear what its purpose is or if it has any additional functionality | t | f | f | . Poor variable and method naming conventions2. No clear purpose or functionality for the class3. Inconsistent use of constructor for both setting and getting ID and name 4. Excessive and repetitive code for setting and getting ID and name variables5. No comments or documentation for the class or methods6. No error handling for setting invalid values for ID or name7. Possible feature envy for the Book class as it only contains getters and setters for two variables, but it is not clear what its purpose is or if it has any additional functionality. | data class | 0 | 12530 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 2 | 1950 | 12530 |
| 1951 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | data class, long method | t | t | f | data class | long method | 0 | 12534 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 1951 | 12534 |
| 1951 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (Multiple calls to isSet methods on external objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy (Multiple calls to isSet methods on external objects) | t | f | t | 0 | 12534 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 1951 | 12534 | ||
| 1956 | { "response": "YES, I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
long method | long method | t | t | t | 0 | 12558 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 1 | 1956 | 12558 | ||
| 1956 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12558 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 2 | 1956 | 12558 | ||
| 1957 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method2 Feature envy3 Primitive obsession | t | f | t | 0 | 12568 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 1957 | 12568 | ||
| 1959 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | 1 Long Method | t | f | t | 0 | 12573 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 1 | 1959 | 12573 | ||
| 1959 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12573 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 2 | 1959 | 12573 | |
| 1960 | { "output": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 12583 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 1 | 1960 | 12583 |
| 1960 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 12583 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 2 | 1960 | 12583 |
| 1962 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | long method | t | t | t | 0 | 12586 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1962 | 12586 | ||
| 1962 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12586 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1962 | 12586 | ||
| 1963 | YES I found bad smells the bad smells are: 1. Feature envy: The method uses multiple attributes and methods from the baseRequest object, indicating a potential violation of the single responsibility principle. 2. Long method: The method is long, spanning over multiple lines and performing multiple tasks, indicating that it may be difficult to read, understand, and maintain. 3. Shotgun surgery: Changing one aspect of the baseRequest object would require changes to this method, indicating a highly coupled code. 4. Magic numbers/string literals: The method uses string literals like "FORWARD_REQUEST_URI" and "ASYNC_REQUEST_URI" to set and get attributes, making it difficult to understand their significance. 5. Inconsistent formatting: The placement of brackets and white spaces is inconsistent, making the code difficult to read and maintain. 6. Code duplication: The code to set the attributes for "uri" and without "uri" is essentially the same, indicating a violation of the DRY (Don't Repeat Yourself) principle. 7. Non-descriptive variable names: The variable names like "baseRequest" and "state" do not convey their purpose, making it difficult to understand the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
feature envy | Feature envy: The method uses multiple attributes and methods from the baseRequest object, indicating a potential violation of the single responsibility principle2 Long method: The method is long, spanning over multiple lines and performing multiple tasks, indicating that it may be difficult to read, understand, and maintain3 Shotgun surgery: Changing one aspect of the baseRequest object would require changes to this method, indicating a highly coupled code4 Magic numbers/string literals: The method uses string literals like "FORWARD_REQUEST_URI" and "ASYNC_REQUEST_URI" to set and get attributes, making it difficult to understand their significance5 Inconsistent formatting: The placement of brackets and white spaces is inconsistent, making the code difficult to read and maintain6 Code duplication: The code to set the attributes for "uri" and without "uri" is essentially the same, indicating a violation of the DRY (Don't Repeat Yourself) principle7 Non-descriptive variable names: The variable names like "baseRequest" and "state" do not convey their purpose, making it difficult to understand the code | t | f | t | indicating a potential violation of the single responsibility principle.2. Long method: The method is long, spanning over multiple lines and performing multiple tasks, indicating that it may be difficult to read, understand, and maintain.3. Shotgun surgery: Changing one aspect of the baseRequest object would require changes to this method, indicating a highly coupled code.4. Magic numbers/string literals: The method uses string literals like "FORWARD_REQUEST_URI" and "ASYNC_REQUEST_URI" to set and get attributes, making it difficult to understand their significance.5. Inconsistent formatting: The placement of brackets and white spaces is inconsistent, making the code difficult to read and maintain.6. Code duplication: The code to set the attributes for "uri" and without "uri" is essentially the same, indicating a violation of the DRY (Don't Repeat Yourself) principle.7. Non-descriptive variable names: The variable names like "baseRequest" and "state" do not convey their purpose, making it difficult to understand the code. | 0 | 12587 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1963 | 12587 | |
| 1965 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | data class, long method | t | t | t | long method | 0 | 12591 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 1965 | 12591 | |
| 1965 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12591 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 1965 | 12591 |
| 1969 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12606 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1969 | 12606 |
| 1969 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long method 2 Feature Envy | t | f | t | 0 | 12606 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1969 | 12606 | ||
| 1970 | { "output": "YES I found bad smells", "message": "the bad smells are:", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12607 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1970 | 12607 | |
| 1970 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12607 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1970 | 12607 | ||
| 1972 | {"output": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | 1. long method | t | t | t | 0 | 12611 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 1 | 1972 | 12611 | ||
| 1972 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12611 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 2 | 1972 | 12611 | ||
| 1973 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12612 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 1 | 1973 | 12612 | ||
| 1973 | YES I found bad smells the bad smells are: None | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | None | t | f | f | None | long method | 0 | 12612 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 2 | 1973 | 12612 |
| 1978 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | data class | t | t | t | 0 | 12631 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 1978 | 12631 | ||
| 1978 | YES, I found bad smells: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 12631 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 1978 | 12631 |
| 1981 | { "message": "YES I found bad smells", "bad_smells": [ { "1": "Data Class" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | 1: data class, 2: long method | t | t | f | 2: long method | data class | 0 | 12639 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 1 | 1981 | 12639 |
| 1981 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 12639 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 2 | 1981 | 12639 |
| 1983 | { "message": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | t | f | f | data class | 0 | 12645 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 1 | 1983 | 12645 | ||
| 1983 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12645 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 2 | 1983 | 12645 |
| 1985 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | 1. long method | t | t | t | 0 | 12651 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 1 | 1985 | 12651 | ||
| 1985 | YES I found bad smells the bad smells are: 1. Duplicated code, 2. Feature envy, 3. Long method, 4. Lazy class, 5. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | Duplicated code, 2 Feature envy, 3 Long method, 4 Lazy class, 5 Long parameter list | t | f | t | . Duplicated code, 2. Feature envy, 4. Lazy class, 5. Long parameter list | 0 | 12651 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 2 | 1985 | 12651 | |
| 1986 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method | t | t | t | 0 | 12657 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1986 | 12657 | ||
| 1986 | YES I found bad smells The bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 12657 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1986 | 12657 |
| 1991 | {"response": "YES I found bad smells", "detected bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | long method, data class | t | t | t | data class | 0 | 12682 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1991 | 12682 | |
| 1991 | YES, I found bad smells The bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Magic numbers (specific values used without explanation) 5. Primitive obsession (using basic data types instead of creating custom classes for data) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Duplicated code2 Long method3 Feature envy4 Magic numbers (specific values used without explanation)5 Primitive obsession (using basic data types instead of creating custom classes for data) | t | f | t | 0 | 12682 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1991 | 12682 | ||
| 1992 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | data class | t | t | t | 0 | 12687 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 1 | 1992 | 12687 | ||
| 1992 | YES I found bad smells the bad smells are: 1. Long class, 2. Data class, 3. Getter and setter methods, 4. Duplicate code, 5. Lack of encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | Long class, 2 Data class, 3 Getter and setter methods, 4 Duplicate code, 5 Lack of encapsulation | t | f | t | . Long class, 3. Getter and setter methods, 4. Duplicate code, 5. Lack of encapsulation. | 0 | 12687 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 2 | 1992 | 12687 | |
| 1993 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12691 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 1993 | 12691 |
| 1993 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | Feature envy | t | f | t | 0 | 12691 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 1993 | 12691 | ||
| 1995 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | 1. data class | t | t | f | data class | 0 | 12696 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 1 | 1995 | 12696 | |
| 1995 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12696 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 2 | 1995 | 12696 |
| 1997 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method | t | t | t | 0 | 12700 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1997 | 12700 | ||
| 1997 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12700 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1997 | 12700 | ||
| 1998 | {} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | f | f | f | long method | 0 | 12702 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 1 | 1998 | 12702 | ||
| 1998 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | f | f | f | long method | 0 | 12702 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 2 | 1998 | 12702 | ||
| 1999 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12705 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 1999 | 12705 | |
| 1999 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12705 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 1999 | 12705 | ||
| 2001 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | long method | t | t | t | 0 | 12710 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 1 | 2001 | 12710 | ||
| 2001 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12710 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 2 | 2001 | 12710 | ||
| 2003 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12716 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 2003 | 12716 | |
| 2003 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Nested loops 4. Use of var instead of specific data types 5. Poor variable names 6. Feature envy 7. Use of deprecated code (such as FSUtils.getRootDir()) 8. Duplicate code (such as using LOG.isTraceEnabled() twice) 9. Use of "continue" statement 10. Complex conditionals (such as if(srcIdx < 0)) 11. Use of hard-coded values (such as Bytes.toBytes()) 12. Catching and throwing generic exceptions (such as IOException) instead of specific ones 13. Use of multiple return statements 14. Inconsistent indentations 15. Use of multiple assignments in one line 16. Use of "else" statements (can be refactored into guard clauses) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Long method2 Magic numbers3 Nested loops4 Use of var instead of specific data types5 Poor variable names6 Feature envy7 Use of deprecated code (such as FSUtilsgetRootDir())8 Duplicate code (such as using LOGisTraceEnabled() twice)9 Use of "continue" statement | t | f | t | 0 | 12716 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 2003 | 12716 | ||
| 2005 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12720 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 2005 | 12720 |
| 2005 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12720 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 2005 | 12720 | ||
| 2006 | {"response":"YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | 1. long method | t | t | f | long method | 0 | 12721 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 2006 | 12721 | |
| 2006 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12721 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 2006 | 12721 | ||
| 2008 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Excessive number of parameters 4. Inconsistent naming conventions 5. Use of raw types 6. Unused imports 7. Lack of documentation/comments 8. Use of regex without clear purpose 9. Unnecessary getters and setters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | Long method2 Feature envy3 Excessive number of parameters4 Inconsistent naming conventions5 Use of raw types6 Unused imports7 Lack of documentation/comments8 Use of regex without clear purpose9 Unnecessary getters and setters | t | f | f | . Long method2. Feature envy3. Excessive number of parameters4. Inconsistent naming conventions5. Use of raw types6. Unused imports7. Lack of documentation/comments8. Use of regex without clear purpose9. Unnecessary getters and setters | data class | 0 | 12738 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 2 | 2008 | 12738 |
| 2011 | { "result": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12750 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 2011 | 12750 | |
| 2011 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Magic number, 4.Multiple nested if statements, 5.Use of a mixture of data types without clear reason, 6.Inconsistent indentation, 7.Duplicate code, 8.Missing comments, 9.Poor error handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method, 2Feature envy, 3Magic number, 4Multiple nested if statements, 5Use of a mixture of data types without clear reason, 6Inconsistent indentation, 7Duplicate code, 8Missing comments, 9Poor error handling | t | f | t | 2.Feature envy, 3.Magic number, 4.Multiple nested if statements, 5.Use of a mixture of data types without clear reason, 6.Inconsistent indentation, 7.Duplicate code, 8.Missing comments, 9.Poor error handling. | 0 | 12750 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 2011 | 12750 | |
| 2012 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12754 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2012 | 12754 |
| 2012 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12754 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2012 | 12754 | ||
| 2013 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method, data class | t | t | t | data class | 0 | 12755 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2013 | 12755 | |
| 2013 | YES I found bad smells the bad smells are: 1. Long method 2. Repetitive code (similar code blocks for different parameters) 3. Data class (the method is only performing data validation, which could be separated into its own class) 4. Feature envy (the use of a different helper class for extracting data) 5. Long parameter list (the method has a large number of parameters) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method2 Repetitive code (similar code blocks for different parameters)3 Data class (the method is only performing data validation, which could be separated into its own class)4 Feature envy (the use of a different helper class for extracting data)5 Long parameter list (the method has a large number of parameters) | t | f | t | which could be separated into its own class)4. Feature envy (the use of a different helper class for extracting data)5. Long parameter list (the method has a large number of parameters) | 0 | 12755 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2013 | 12755 | |
| 2015 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | 1: long method | t | t | f | long method | 0 | 12768 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2015 | 12768 | |
| 2015 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12768 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2015 | 12768 | ||
| 2019 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12781 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 1 | 2019 | 12781 |
| 2019 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method, 3.Magic number, 4.Duplicate code, 5.Inconsistent formatting, 6.Unnecessary constructors, 7.Unformatted comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | Feature envy, 2Long method, 3Magic number, 4Duplicate code, 5Inconsistent formatting, 6Unnecessary constructors, 7Unformatted comments | t | f | f | .Feature envy, 2.Long method, 3.Magic number, 4.Duplicate code, 5.Inconsistent formatting, 6.Unnecessary constructors, 7.Unformatted comments | data class | 0 | 12781 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 2 | 2019 | 12781 |
| 2020 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | data class | t | t | t | 0 | 12785 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 2020 | 12785 | ||
| 2020 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12785 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 2020 | 12785 |
| 2021 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 12790 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 2021 | 12790 | ||
| 2021 | YES I found bad smells the bad smells are: 7. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | 7 Feature envy | t | f | f | 7. Feature envy | long method | 0 | 12790 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 2021 | 12790 |
| 2023 | "YES I found bad smells" the bad smells are: 1. Magic numbers 2. Hard-coded string literals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | Magic numbers2 Hard-coded string literals | t | f | f | . Magic numbers2. Hard-coded string literals | feature envy | 0 | 12796 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 2023 | 12796 |
| 2025 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 12800 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 1 | 2025 | 12800 |
| 2025 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | Long method, 2Magic numbers | t | f | f | .Long method, 2.Magic numbers | feature envy | 0 | 12800 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 2 | 2025 | 12800 |
| 2026 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 12803 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 1 | 2026 | 12803 | |
| 2026 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement with repeated code 3. Use of raw type 4. Magic number/unnamed constants 5. Use of multiple return statements within a method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
feature envy | Long method2 Switch statement with repeated code3 Use of raw type4 Magic number/unnamed constants5 Use of multiple return statements within a method | t | f | f | . Long method2. Switch statement with repeated code3. Use of raw type4. Magic number/unnamed constants5. Use of multiple return statements within a method | feature envy | 0 | 12803 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 2 | 2026 | 12803 |
| 2027 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12805 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 1 | 2027 | 12805 |
| 2027 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Switch statement 3. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | Magic numbers2 Switch statement3 Long method | t | f | f | . Magic numbers2. Switch statement3. Long method | feature envy | 0 | 12805 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 2 | 2027 | 12805 |
| 2028 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12806 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 2028 | 12806 |
| 2028 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 12806 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 2028 | 12806 | ||
| 2029 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | long method | t | t | t | 0 | 12807 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 2029 | 12807 | ||
| 2029 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Magic strings | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method, 2Magic numbers, 3Magic strings | t | f | t | 2.Magic numbers, 3.Magic strings | 0 | 12807 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 2029 | 12807 | |
| 2030 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "3. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | 3. long method | t | t | f | 3. long method | data class | 0 | 12809 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 2030 | 12809 |
| 2030 | YES I found bad smells the bad smells are: 1. Feature envy - The getSharedSecret() and setSharedSecret() methods are only accessing and modifying the sharedSecret variable, which is not a part of this class. This could potentially lead to issues with data consistency and violates the principle of encapsulation. 2. Long method - The class contains multiple methods with a significant amount of code, making it difficult to read and maintain. 3. Magic numbers - The tokenExpirationSeconds and the minimum length for the shared secret are set with arbitrary values, making it unclear why those specific values were chosen. 4. Inconsistent formatting - Some methods have Javadoc comments, while others do not. This inconsistency can make the code harder to read and understand. 5. Unused code - The isAppropriateForCreating() and isAppropriateForValidating() methods are not utilized in the class and can be considered dead code. 6. Misleading method names - The getCertPath() and getKeyPath() methods imply that they are retrieving paths, but they are actually returning the actual data contained in those files. A more accurate name for these methods would be getCertificate() and getPrivateKey(). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | Feature envy - The getSharedSecret() and setSharedSecret() methods are only accessing and modifying the sharedSecret variable, which is not a part of this class This could potentially lead to issues with data consistency and violates the principle of encapsulation2 Long method - The class contains multiple methods with a significant amount of code, making it difficult to read and maintain3 Magic numbers - The tokenExpirationSeconds and the minimum length for the shared secret are set with arbitrary values, making it unclear why those specific values were chosen4 Inconsistent formatting - Some methods have Javadoc comments, while others do not This inconsistency can make the code harder to read and understand5 Unused code - The isAppropriateForCreating() and isAppropriateForValidating() methods are not utilized in the class and can be considered dead code6 Misleading method names - The getCertPath() and getKeyPath() methods imply that they are retrieving paths, but they are actually returning the actual data contained in those files A more accurate name for these methods would be getCertificate() and getPrivateKey() | t | f | f | . Feature envy - The getSharedSecret() and setSharedSecret() methods are only accessing and modifying the sharedSecret variable, which is not a part of this class. This could potentially lead to issues with data consistency and violates the principle of encapsulation.2. Long method - The class contains multiple methods with a significant amount of code, making it difficult to read and maintain.3. Magic numbers - The tokenExpirationSeconds and the minimum length for the shared secret are set with arbitrary values, making it unclear why those specific values were chosen.4. Inconsistent formatting - Some methods have Javadoc comments, while others do not. This inconsistency can make the code harder to read and understand.5. Unused code - The isAppropriateForCreating() and isAppropriateForValidating() methods are not utilized in the class and can be considered dead code.6. Misleading method names - The getCertPath() and getKeyPath() methods imply that they are retrieving paths, but they are actually returning the actual data contained in those files. A more accurate name for these methods would be getCertificate() and getPrivateKey(). | data class | 0 | 12809 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 2030 | 12809 |
| 2031 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class WithName extends INodeReference { private final byte[] name; /** * The id of the last snapshot in the src tree when this WithName node was * generated. When calculating the quota usage of the referred node, only * the files/dirs existing when this snapshot was taken will be counted for * this WithName node and propagated along its ancestor path. */ private final int lastSnapshotId; public WithName(INodeDirectory parent, WithCount referred, byte[] name, int lastSnapshotId) { super(parent, referred); this.name = name; this.lastSnapshotId = lastSnapshotId; referred.addReference(this); } @Override public final byte[] getLocalNameBytes() { return name; } @Override public final void setLocalName(byte[] name) { throw new UnsupportedOperationException("Cannot set name: " + getClass() + " is immutable."); } public int getLastSnapshotId() { return lastSnapshotId; } @Override public final ContentSummaryComputationContext computeContentSummary( int snapshotId, ContentSummaryComputationContext summary) { final int s = snapshotId < lastSnapshotId ? snapshotId : lastSnapshotId; // only count storagespace for WithName final QuotaCounts q = computeQuotaUsage( summary.getBlockStoragePolicySuite(), getStoragePolicyID(), false, s); summary.getCounts().addContent(Content.DISKSPACE, q.getStorageSpace()); summary.getCounts().addTypeSpaces(q.getTypeSpaces()); return summary; } @Override public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps, byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) { // if this.lastSnapshotId < lastSnapshotId, the rename of the referred // node happened before the rename of its ancestor. This should be // impossible since for WithName node we only count its children at the // time of the rename. Preconditions.checkState(lastSnapshotId == Snapshot.CURRENT_STATE_ID || this.lastSnapshotId >= lastSnapshotId); final INode referred = this.getReferredINode().asReference() .getReferredINode(); // We will continue the quota usage computation using the same snapshot id // as time line (if the given snapshot id is valid). Also, we cannot use // cache for the referred node since its cached quota may have already // been updated by changes in the current tree. int id = lastSnapshotId != Snapshot.CURRENT_STATE_ID ? lastSnapshotId : this.lastSnapshotId; return referred.computeQuotaUsage(bsps, blockStoragePolicyId, false, id); } @Override public void cleanSubtree(ReclaimContext reclaimContext, final int snapshot, int prior) { // since WithName node resides in deleted list acting as a snapshot copy, // the parameter snapshot must be non-null Preconditions.checkArgument(snapshot != Snapshot.CURRENT_STATE_ID); // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to the // previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } if (prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } // record the old quota delta QuotaCounts old = reclaimContext.quotaDelta().getCountsCopy(); getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { QuotaCounts current = reclaimContext.quotaDelta().getCountsCopy(); current.subtract(old); // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, current); } if (snapshot < lastSnapshotId) { // for a WithName node, when we compute its quota usage, we only count // in all the nodes existing at the time of the corresponding rename op. // Thus if we are deleting a snapshot before/at the snapshot associated // with lastSnapshotId, we do not need to update the quota upwards. reclaimContext.quotaDelta().setCounts(old); } } @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { int snapshot = getSelfSnapshot(); reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(reclaimContext.getCopy()); } else { int prior = getPriorSnapshot(this); INode referred = getReferredINode().asReference().getReferredINode(); if (snapshot != Snapshot.NO_SNAPSHOT_ID) { if (prior != Snapshot.NO_SNAPSHOT_ID && snapshot <= prior) { // the snapshot to be deleted has been deleted while traversing // the src tree of the previous rename operation. This usually // happens when rename's src and dst are under the same // snapshottable directory. E.g., the following operation sequence: // 1. create snapshot s1 on /test // 2. rename /test/foo/bar to /test/foo2/bar // 3. create snapshot s2 on /test // 4. rename foo2 again // 5. delete snapshot s2 return; } ReclaimContext newCtx = reclaimContext.getCopy(); referred.cleanSubtree(newCtx, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, newCtx.quotaDelta().getCountsCopy()); } } } } private int getSelfSnapshot() { INode referred = getReferredINode().asReference().getReferredINode(); int snapshot = Snapshot.NO_SNAPSHOT_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { snapshot = referred.asFile().getDiffs().getPrior(lastSnapshotId); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { snapshot = sf.getDiffs().getPrior(lastSnapshotId); } } return snapshot; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12811 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java/#L466-L619 | 1 | 2031 | 12811 |
| 2031 | YES I found bad smells The bad smells are: 1. Long method (computeContentSummary) 2. Feature envy (in computeContentSummary and computeQuotaUsage methods) 3. Duplicate code (in computeQuotaUsage method) 4. Data class (INodeReference class has only private fields and getters/setters) 5. Primitive obsession (use of bytes instead of a custom class for names) 6. Refused bequest (overriding methods unnecessarily in WithName class) 7. Null checks and fail-fast behavior (in cleanSubtree and destroyAndCollectBlocks methods) 8. Intensive coupling (reliance on specific methods and classes) 9. Inconsistent naming of methods and variables 10. Use of final keyword unnecessarily. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class WithName extends INodeReference { private final byte[] name; /** * The id of the last snapshot in the src tree when this WithName node was * generated. When calculating the quota usage of the referred node, only * the files/dirs existing when this snapshot was taken will be counted for * this WithName node and propagated along its ancestor path. */ private final int lastSnapshotId; public WithName(INodeDirectory parent, WithCount referred, byte[] name, int lastSnapshotId) { super(parent, referred); this.name = name; this.lastSnapshotId = lastSnapshotId; referred.addReference(this); } @Override public final byte[] getLocalNameBytes() { return name; } @Override public final void setLocalName(byte[] name) { throw new UnsupportedOperationException("Cannot set name: " + getClass() + " is immutable."); } public int getLastSnapshotId() { return lastSnapshotId; } @Override public final ContentSummaryComputationContext computeContentSummary( int snapshotId, ContentSummaryComputationContext summary) { final int s = snapshotId < lastSnapshotId ? snapshotId : lastSnapshotId; // only count storagespace for WithName final QuotaCounts q = computeQuotaUsage( summary.getBlockStoragePolicySuite(), getStoragePolicyID(), false, s); summary.getCounts().addContent(Content.DISKSPACE, q.getStorageSpace()); summary.getCounts().addTypeSpaces(q.getTypeSpaces()); return summary; } @Override public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps, byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) { // if this.lastSnapshotId < lastSnapshotId, the rename of the referred // node happened before the rename of its ancestor. This should be // impossible since for WithName node we only count its children at the // time of the rename. Preconditions.checkState(lastSnapshotId == Snapshot.CURRENT_STATE_ID || this.lastSnapshotId >= lastSnapshotId); final INode referred = this.getReferredINode().asReference() .getReferredINode(); // We will continue the quota usage computation using the same snapshot id // as time line (if the given snapshot id is valid). Also, we cannot use // cache for the referred node since its cached quota may have already // been updated by changes in the current tree. int id = lastSnapshotId != Snapshot.CURRENT_STATE_ID ? lastSnapshotId : this.lastSnapshotId; return referred.computeQuotaUsage(bsps, blockStoragePolicyId, false, id); } @Override public void cleanSubtree(ReclaimContext reclaimContext, final int snapshot, int prior) { // since WithName node resides in deleted list acting as a snapshot copy, // the parameter snapshot must be non-null Preconditions.checkArgument(snapshot != Snapshot.CURRENT_STATE_ID); // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to the // previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } if (prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } // record the old quota delta QuotaCounts old = reclaimContext.quotaDelta().getCountsCopy(); getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { QuotaCounts current = reclaimContext.quotaDelta().getCountsCopy(); current.subtract(old); // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, current); } if (snapshot < lastSnapshotId) { // for a WithName node, when we compute its quota usage, we only count // in all the nodes existing at the time of the corresponding rename op. // Thus if we are deleting a snapshot before/at the snapshot associated // with lastSnapshotId, we do not need to update the quota upwards. reclaimContext.quotaDelta().setCounts(old); } } @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { int snapshot = getSelfSnapshot(); reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(reclaimContext.getCopy()); } else { int prior = getPriorSnapshot(this); INode referred = getReferredINode().asReference().getReferredINode(); if (snapshot != Snapshot.NO_SNAPSHOT_ID) { if (prior != Snapshot.NO_SNAPSHOT_ID && snapshot <= prior) { // the snapshot to be deleted has been deleted while traversing // the src tree of the previous rename operation. This usually // happens when rename's src and dst are under the same // snapshottable directory. E.g., the following operation sequence: // 1. create snapshot s1 on /test // 2. rename /test/foo/bar to /test/foo2/bar // 3. create snapshot s2 on /test // 4. rename foo2 again // 5. delete snapshot s2 return; } ReclaimContext newCtx = reclaimContext.getCopy(); referred.cleanSubtree(newCtx, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, newCtx.quotaDelta().getCountsCopy()); } } } } private int getSelfSnapshot() { INode referred = getReferredINode().asReference().getReferredINode(); int snapshot = Snapshot.NO_SNAPSHOT_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { snapshot = referred.asFile().getDiffs().getPrior(lastSnapshotId); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { snapshot = sf.getDiffs().getPrior(lastSnapshotId); } } return snapshot; } } |
data class | Long method (computeContentSummary)2 Feature envy (in computeContentSummary and computeQuotaUsage methods)3 Duplicate code (in computeQuotaUsage method)4 Data class (INodeReference class has only private fields and getters/setters)5 Primitive obsession (use of bytes instead of a custom class for names)6 Refused bequest (overriding methods unnecessarily in WithName class)7 Null checks and fail-fast behavior (in cleanSubtree and destroyAndCollectBlocks methods)8 Intensive coupling (reliance on specific methods and classes)9 Inconsistent naming of methods and variables | t | f | t | 0 | 12811 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java/#L466-L619 | 2 | 2031 | 12811 | ||
| 2034 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | data class | t | t | t | 0 | 12827 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 1 | 2034 | 12827 | ||
| 2034 | YES I found bad smells the bad smells are: 1. Public access modifier for inner class 2. Non-descriptive class and method names 3. Abstract method with no implementation 4. Abstract class with no non-abstract methods 5. Lack of comments/documentation 6. Class not following standard Java naming conventions (missing CamelCase) 7. Lack of proper encapsulation of fields in inner class 8. Use of static class for no apparent reason | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | Public access modifier for inner class2 Non-descriptive class and method names3 Abstract method with no implementation4 Abstract class with no non-abstract methods5 Lack of comments/documentation6 Class not following standard Java naming conventions (missing CamelCase)7 Lack of proper encapsulation of fields in inner class8 Use of static class for no apparent reason | t | f | f | . Public access modifier for inner class2. Non-descriptive class and method names3. Abstract method with no implementation4. Abstract class with no non-abstract methods5. Lack of comments/documentation6. Class not following standard Java naming conventions (missing CamelCase)7. Lack of proper encapsulation of fields in inner class8. Use of static class for no apparent reason | data class | 0 | 12827 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 2 | 2034 | 12827 |
| 2035 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 12828 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 1 | 2035 | 12828 |
| 2035 | YES I found bad smells. the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 12828 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 2 | 2035 | 12828 |
| 2037 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | long method | t | t | t | 0 | 12838 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 2037 | 12838 | ||
| 2037 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Lack of comments/documentation 6. Inadequate naming convention 7. Use of raw types 8. Inconsistent formatting/indentation 9. unnecessary temporary variables 10. Empty catch blocks 11. Inconsistent use of logging 12. Use of non-descriptive/misleading variable names 13. Use of wildcard imports 14. Excessive and unnecessary nesting 15. Lack of error handling/exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Magic numbers 5 Lack of comments/documentation 6 Inadequate naming convention 7 Use of raw types 8 Inconsistent formatting/indentation 9 unnecessary temporary variables | t | f | t | 0 | 12838 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 2037 | 12838 | ||
| 2038 | Yes, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12843 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 2038 | 12843 |
| 2040 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Long parameter list 4. Conditional complexity 5. Feature envy 6. Primitive obsession 7. Magic numbers/constants | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method 2 Duplicate code 3 Long parameter list 4 Conditional complexity 5 Feature envy 6 Primitive obsession7 Magic numbers/constants | t | f | t | 0 | 12850 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 2040 | 12850 | ||
| 2041 | YES, I found bad smells. The bad smells are: 1. Feature envy: the methods within the GridMBeanServerData class are mostly only accessing and manipulating data within that class, which suggests that these methods should be moved into the class itself to avoid feature envy. 2. Long method: the GridMBeanServerData constructor, while not excessively long, could still benefit from being broken down into smaller methods for clarity and maintainability. 3. Magic numbers: the value for the initial capacity in the HashSet creation is a magic number and should be given a descriptive variable name. 4. No encapsulation: the fields in the GridMBeanServerData class are set to public, which could lead to potential issues if these fields are accidentally manipulated by external classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | Feature envy: the methods within the GridMBeanServerData class are mostly only accessing and manipulating data within that class, which suggests that these methods should be moved into the class itself to avoid feature envy2 Long method: the GridMBeanServerData constructor, while not excessively long, could still benefit from being broken down into smaller methods for clarity and maintainability3 Magic numbers: the value for the initial capacity in the HashSet creation is a magic number and should be given a descriptive variable name4 No encapsulation: the fields in the GridMBeanServerData class are set to public, which could lead to potential issues if these fields are accidentally manipulated by external classes | t | f | t | which suggests that these methods should be moved into the class itself to avoid feature envy.2. Long method: the GridMBeanServerData constructor, while not excessively long, which could lead to potential issues if these fields are accidentally manipulated by external classes. | 0 | 12853 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 2 | 2041 | 12853 | |
| 2042 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | 1. long method | t | t | t | 0 | 12854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 2042 | 12854 | ||
| 2042 | the bad smells are: 1. Long method 2. Duplicate code 3. Complex conditional logic 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Duplicate code3 Complex conditional logic4 Feature envy | f | f | t | 0 | 12854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 2042 | 12854 | ||
| 2044 | {"message":"YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 12869 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 2044 | 12869 |
| 2045 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | long method | t | t | f | long method | data class | 0 | 12871 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 2045 | 12871 |
| 2045 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inappropriate comments 6. Data class 7. Many parameters 8. Primitive obsession 9. Dead code 10. Null pointer exceptions 11. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Inappropriate comments6 Data class7 Many parameters8 Primitive obsession9 Dead code | t | f | t | 0 | 12871 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 2045 | 12871 | ||
| 2046 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | 1. long method | t | t | t | 0 | 12872 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 1 | 2046 | 12872 | ||
| 2046 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers/strings 3. Feature envy 4. Testing multiple scenarios within a single test method 5. Lack of proper comments/documentation 6. Lack of clear and concise variable names 7. Unnecessary/redundant code (e.g. using assertEquals and assertTrue separately when the same result can be achieved with a single assertion) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | Long method2 Magic numbers/strings3 Feature envy4 Testing multiple scenarios within a single test method5 Lack of proper comments/documentation6 Lack of clear and concise variable names7 Unnecessary/redundant code (eg using assertEquals and assertTrue separately when the same result can be achieved with a single assertion) | t | f | t | 0 | 12872 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 2 | 2046 | 12872 | ||
| 2047 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 12877 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 2047 | 12877 |
| 2047 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Primitive obsession 4. Feature envy 5. Dead code 6. Inconsistent indentation 7. Magic numbers 8. Code duplication 9. Large parameter list 10. Improper naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | Long method2 Data class3 Primitive obsession4 Feature envy5 Dead code6 Inconsistent indentation7 Magic numbers8 Code duplication9 Large parameter list | t | f | t | 0 | 12877 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 2047 | 12877 | ||
| 2048 | { "error": "Sorry, I cannot analyze the provided Java code to identify bad smells. You may want to use a specialized code analysis tool for this task." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | f | f | f | long method | 0 | 12878 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 2048 | 12878 | ||
| 2048 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Use of nested maps and loops, which can make the code difficult to read and maintain 4. Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component 5. Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality. 6. Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java. 7. Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy3 Use of nested maps and loops, which can make the code difficult to read and maintain4 Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component5 Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality6 Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java7 Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers | t | f | t | which can make the code difficult to read and maintain4. Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component5. Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality.6. Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java.7. Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers. | 0 | 12878 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 2048 | 12878 | |
| 2050 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
long method | long method | t | t | t | 0 | 12885 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 1 | 2050 | 12885 | ||
| 2050 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12885 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 2 | 2050 | 12885 | ||
| 2051 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | data class | t | t | t | 0 | 12894 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 1 | 2051 | 12894 | ||
| 2051 | YES I found bad smells The bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy. | data class | 0 | 12894 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 2 | 2051 | 12894 |
| 2052 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 12902 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 2 | 2052 | 12902 |
| 2052 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | long method, data class | t | t | t | long method | 0 | 12902 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 1 | 2052 | 12902 | |
| 2053 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
long method | \n1. long method | t | t | f | long method | 0 | 12903 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 1 | 2053 | 12903 | |
| 2053 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12903 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 2 | 2053 | 12903 | ||
| 2054 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | data class | t | t | t | 0 | 12922 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 1 | 2054 | 12922 | ||
| 2054 | YES I found bad smells, the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 12922 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 2 | 2054 | 12922 |
| 2055 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | long method | t | t | t | 0 | 12939 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 2055 | 12939 | ||
| 2055 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12939 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 2055 | 12939 | ||
| 2056 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12950 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 1 | 2056 | 12950 |
| 2056 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | Feature envy, 2Long parameter list | t | f | f | .Feature envy, 2.Long parameter list | data class | 0 | 12950 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 2 | 2056 | 12950 |
| 2057 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 12952 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 1 | 2057 | 12952 | ||
| 2057 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12952 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 2 | 2057 | 12952 |
| 2058 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | data class | t | t | t | 0 | 12960 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 2058 | 12960 | ||
| 2058 | YES I found bad smells the bad smells are: 1. Long Parameter List 2. Long Method 3. Data Class 4. Feature Envy 5. Switch Statements 6. Lazy Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long Parameter List2 Long Method3 Data Class4 Feature Envy5 Switch Statements6 Lazy Class | t | f | t | 0 | 12960 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 2058 | 12960 | ||
| 2059 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | f | f | f | data class | 0 | 12962 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 2 | 2059 | 12962 | ||
| 2060 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | data class | t | t | t | 0 | 12964 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 2060 | 12964 | ||
| 2060 | YES I found bad smells. the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 12964 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 2060 | 12964 |
| 2061 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | 1. data class | t | t | f | data class | 0 | 12970 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 2061 | 12970 | |
| 2061 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 12970 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 2061 | 12970 |
| 2062 | { "message": "YES I found bad smells", "bad smells are": "2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | 2. data class | t | t | f | 2. data class | long method | 0 | 12975 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 1 | 2062 | 12975 |
| 2062 | YES, I found bad smells 1. Conditional complexity 2. Duplicate code 3. Long method 4. Long parameter list 5. Primitive obsession 6. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | Conditional complexity2 Duplicate code 3 Long method 4 Long parameter list 5 Primitive obsession 6 Feature envy | t | f | t | 0 | 12975 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 2 | 2062 | 12975 | ||
| 2065 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | 1. long method | t | t | t | 0 | 12987 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 1 | 2065 | 12987 | ||
| 2065 | YES I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 12987 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 2 | 2065 | 12987 | ||
| 2066 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | data class, long method | t | t | t | long method | 0 | 12994 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 1 | 2066 | 12994 | |
| 2066 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12994 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 2 | 2066 | 12994 |
| 2067 | -13 Long method the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | 3 Long methodthe bad smells are: | f | f | f | 3 Long methodthe bad smells are: | data class | 0 | 12996 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 2 | 2067 | 12996 |
| 2067 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 12996 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 1 | 2067 | 12996 |
| 2069 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | f | f | f | data class | 0 | 13004 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 1 | 2069 | 13004 | ||
| 2069 | YES I found bad smells the bad smells are: 1. Long class 2. Duplicate code (in methods setTargetUri and getTargetUris) 3. Temporary fields (in methods getTargetUri and getTargetUris) 4. Data class (all getter and setter methods with no logic or manipulation of data) 5. Misplaced field (field flowRefreshed could potentially be better placed in RemoteProcessGroupContentsDTO class) 6. Long parameter list (constructor with multiple parameters) 7. Feature envy (methods in RemoteProcessGroupContentsDTO class that could potentially be moved to this class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | Long class2 Duplicate code (in methods setTargetUri and getTargetUris)3 Temporary fields (in methods getTargetUri and getTargetUris)4 Data class (all getter and setter methods with no logic or manipulation of data)5 Misplaced field (field flowRefreshed could potentially be better placed in RemoteProcessGroupContentsDTO class)6 Long parameter list (constructor with multiple parameters)7 Feature envy (methods in RemoteProcessGroupContentsDTO class that could potentially be moved to this class) | t | f | t | 0 | 13004 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 2069 | 13004 | ||
| 2070 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | long method | t | t | t | 0 | 13017 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 2070 | 13017 | ||
| 2070 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13017 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 2070 | 13017 | ||
| 2071 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | data class | t | t | f | data class | long method | 0 | 13025 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2071 | 13025 |
| 2071 | YES I found bad smells the bad smells are: 1)Long method 2)Feature envy 3)Repeated code 4)Naming inconsistencies (e.g. hashKeyValue vs hashKeyName) 5)Multiple responsibilities (method is handling both DynamoDB operations and transferring flowFiles) 6)Catching generic exceptions instead of specific ones 7)Poor code organization (order of variable declarations and logic is not clear) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | )Long method 2)Feature envy 3)Repeated code 4)Naming inconsistencies (eg hashKeyValue vs hashKeyName) 5)Multiple responsibilities (method is handling both DynamoDB operations and transferring flowFiles) 6)Catching generic exceptions instead of specific ones 7)Poor code organization (order of variable declarations and logic is not clear) | t | f | t | 0 | 13025 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2071 | 13025 | ||
| 2072 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | long method | t | t | t | 0 | 13027 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 2072 | 13027 | ||
| 2072 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13027 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 2072 | 13027 | ||
| 2073 | {"response": "YES I found bad smells", "bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | long method | t | t | f | long method | data class | 0 | 13034 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 2 | 2073 | 13034 |
| 2073 | { "response": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | data class, long method | t | t | t | long method | 0 | 13034 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 1 | 2073 | 13034 | |
| 2074 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 13036 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 1 | 2074 | 13036 | |
| 2074 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13036 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 2 | 2074 | 13036 |
| 2076 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | data class | t | t | t | 0 | 13050 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 1 | 2076 | 13050 | ||
| 2076 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13050 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 2 | 2076 | 13050 |
| 2077 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "SerializationRegistrationType", "2. Data Class": "Serializer", "3. Data Class": "Instantiator" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | 1. long method: serializationregistrationtype, 2. data class: serializer, 3. data class: instantiator | t | t | f | 1. long method: serializationregistrationtype | data class | 0 | 13052 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 1 | 2077 | 13052 |
| 2077 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in Instantiator and Serializer classes) 4. Useless comments (e.g. "possible object is" and "allowed object is" in Instantiator and Serializer classes) 5. Inconsistent indentation 6. Lack of proper exception handling 7. Inadequate variable names (e.g. "className" instead of "serializerClassName" in Serializer class) 8. Incomplete documentation (e.g. there is no description of what this class is used for) 9. Possible violation of Single Responsibility Principle (the class seems to have multiple responsibilities, such as storing serializers and instantiators) 10. Possible violation of Open/Closed Principle (if new types of serializers or instantiators are added, changes will need to be made to this class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | Long method2 Feature envy3 Duplicate code (in Instantiator and Serializer classes)4 Useless comments (eg "possible object is" and "allowed object is" in Instantiator and Serializer classes)5 Inconsistent indentation6 Lack of proper exception handling7 Inadequate variable names (eg "className" instead of "serializerClassName" in Serializer class)8 Incomplete documentation (eg there is no description of what this class is used for)9 Possible violation of Single Responsibility Principle (the class seems to have multiple responsibilities, such as storing serializers and instantiators) | t | f | f | . Long method2. Feature envy3. Duplicate code (in Instantiator and Serializer classes)4. Useless comments (e.g. "possible object is" and "allowed object is" in Instantiator and Serializer classes)5. Inconsistent indentation6. Lack of proper exception handling7. Inadequate variable names (e.g. "className" instead of "serializerClassName" in Serializer class)8. Incomplete documentation (e.g. there is no description of what this class is used for)9. Possible violation of Single Responsibility Principle (the class seems to have multiple responsibilities, such as storing serializers and instantiators) | data class | 0 | 13052 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 2077 | 13052 |
| 2078 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | long method | t | t | t | 0 | 13053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 2078 | 13053 | ||
| 2078 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 2078 | 13053 | ||
| 2079 | {"response": "YES I found bad smells", "bad_smells": ["1. Long method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | 1. long method, 2. data class | t | t | f | 1. long method | data class | 0 | 13060 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 2079 | 13060 |
| 2079 | YES I found bad smells, the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 13060 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 2079 | 13060 |
| 2080 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | data class, long method | t | t | t | long method | 0 | 13068 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 1 | 2080 | 13068 | |
| 2080 | YES, I found bad smells. The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 13068 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 2 | 2080 | 13068 |
| 2084 | YES, I found bad smells the bad smells are: 1. Long data class, 2. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | Long data class, 2 Primitive obsession | t | f | t | 2. Primitive obsession | 0 | 13082 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 2 | 2084 | 13082 | |
| 2086 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13101 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 1 | 2086 | 13101 |
| 2086 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 13101 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 2 | 2086 | 13101 |
| 2087 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 13106 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 1 | 2087 | 13106 | ||
| 2087 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Use of unneeded comments 6. Too many parameters in constructor 7. Use of field setters instead of encapsulation 8. Not following object-oriented principles (e.g. workspaceName and workspaceOwner should be in a separate class instead of individual fields in this class) 9. Poor exception handling 10. Lack of cohesion (class is responsible for both writing and setting fields) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | Long method2 Feature envy3 Duplicate code4 Inconsistent naming conventions5 Use of unneeded comments6 Too many parameters in constructor7 Use of field setters instead of encapsulation8 Not following object-oriented principles (eg workspaceName and workspaceOwner should be in a separate class instead of individual fields in this class)9 Poor exception handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent naming conventions5. Use of unneeded comments6. Too many parameters in constructor7. Use of field setters instead of encapsulation8. Not following object-oriented principles (e.g. workspaceName and workspaceOwner should be in a separate class instead of individual fields in this class)9. Poor exception handling | data class | 0 | 13106 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 2 | 2087 | 13106 |
| 2088 | {"response": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13108 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 1 | 2088 | 13108 |
| 2088 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code (in the if statement) 4. Magic numbers (100, 2, etc.) 5. Inconsistent formatting (braces placement) 6. Inconsistent naming conventions (getLastMessageIdAsync vs getLastMessageIdFuture) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | Feature envy2 Long method3 Duplicate code (in the if statement)4 Magic numbers ( | t | f | t | 0 | 13108 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 2 | 2088 | 13108 | ||
| 2089 | { "response": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13117 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 2 | 2089 | 13117 | |
| 2094 | {"response": "YES, I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13142 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 2094 | 13142 |
| 2094 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent spacing and formatting 4. Multiple parameters in method signature 5. Mixing of different responsibilities (writing JSON, getting services, parsing status line) 6. Lack of use of constants for repeated strings (e.g. "data", "serviceCount", "status") 7. Potentially inefficient use of for loop when iterating over services array 8. Nested if statement with multiple conditions 9. Missing error handling for IOException 10. Indirect variable access (accessing Locale object through ServiceReference instead of passing directly) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | Long method2 Feature envy3 Inconsistent spacing and formatting4 Multiple parameters in method signature5 Mixing of different responsibilities (writing JSON, getting services, parsing status line)6 Lack of use of constants for repeated strings (eg "data", "serviceCount", "status")7 Potentially inefficient use of for loop when iterating over services array8 Nested if statement with multiple conditions 9 Missing error handling for IOException | t | f | t | getting services, parsing status line)6. Lack of use of constants for repeated strings (e.g. "data", "serviceCount", "status")7. Potentially inefficient use of for loop when iterating over services array8. Nested if statement with multiple conditions 9. Missing error handling for IOException | 0 | 13142 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 2094 | 13142 | |
| 2095 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | data class | t | t | t | 0 | 13145 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 1 | 2095 | 13145 | ||
| 2095 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13145 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 2 | 2095 | 13145 |
| 2096 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13148 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 1 | 2096 | 13148 |
| 2096 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13148 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 2 | 2096 | 13148 | ||
| 2097 | {"response": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Map4 extends Map3 { /** */ private static final long serialVersionUID = 0L; /** */ protected K k4; /** */ protected V v4; /** * Constructs map. */ Map4() { // No-op. } /** * Constructs map. * * @param k1 Key1. * @param v1 Value1. * @param k2 Key2. * @param v2 Value2. * @param k3 Key3. * @param v3 Value3. * @param k4 Key4. * @param v4 Value4. */ Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { super(k1, v1, k2, v2, k3, v3); this.k4 = k4; this.v4 = v4; } /** {@inheritDoc} */ @Override public boolean isFull() { return size() == 4; } /** {@inheritDoc} */ @Nullable @Override public V remove(Object key) { if (F.eq(key, k4)) { V res = v4; v4 = null; k4 = null; return res; } return super.remove(key); } /** {@inheritDoc} */ @Override public int size() { return super.size() + (k4 != null ? 1 : 0); } /** {@inheritDoc} */ @Override public boolean containsKey(Object k) { return super.containsKey(k) || (k4 != null && F.eq(k, k4)); } /** {@inheritDoc} */ @Override public boolean containsValue(Object v) { return super.containsValue(v) || (k4 != null && F.eq(v, v4)); } /** {@inheritDoc} */ @Nullable @Override public V get(Object k) { V v = super.get(k); return v != null ? v : (k4 != null && F.eq(k, k4)) ? v4 : null; } /** * Puts key-value pair into map only if given key is already contained in the map * or there are free slots. * Note that this implementation of {@link Map#put(Object, Object)} does not match * general contract of {@link Map} interface and serves only for internal purposes. * * @param key Key. * @param val Value. * @return Previous value associated with given key. */ @Nullable @Override public V put(K key, V val) throws NullPointerException { V oldVal = get(key); if (k1 == null || F.eq(k1, key)) { k1 = key; v1 = val; } else if (k2 == null || F.eq(k2, key)) { k2 = key; v2 = val; } else if (k3 == null || F.eq(k3, key)) { k3 = key; v3 = val; } else if (k4 == null || F.eq(k4, key)) { k4 = key; v4 = val; } return oldVal; } /** {@inheritDoc} */ @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { private int idx; private Entry next; { if (k1 != null) { idx = 1; next = e(k1, v1); } else if (k2 != null) { idx = 2; next = e(k2, v2); } else if (k3 != null) { idx = 3; next = e(k3, v3); } else if (k4 != null) { idx = 4; next = e(k4, v4); } } @Override public boolean hasNext() { return next != null; } @SuppressWarnings("fallthrough") @Override public Entry next() { if (!hasNext()) throw new NoSuchElementException(); Entry old = next; next = null; switch (idx) { case 1: if (k2 != null) { idx = 2; next = e(k2, v2); break; } case 2: if (k3 != null) { idx = 3; next = e(k3, v3); break; } case 3: if (k4 != null) { idx = 4; next = e(k4, v4); break; } } return old; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return Map4.this.size(); } }; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 13149 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/util/GridLeanMap.java/#L836-L1027 | 1 | 2097 | 13149 |
| 2097 | YES, I found bad smells. the bad smells are: 1. Long class 2. Long method 3. Feature envy 4. Inconsistent naming conventions 5. Unnecessary comments 6. Data class 7. Frequent use of conditional statements and null checks 8. Complex and convoluted code logic 9. Violation of Liskov substitution principle (subclass Map4 does not strictly adhere to the behavior of its superclass Map3) 10. Use of raw types (set of raw type AbstractSet is used without specifying its generic type) 11. Violation of single responsibility principle (Map4 class handles both map data structure and internal iterator logic) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Map4 extends Map3 { /** */ private static final long serialVersionUID = 0L; /** */ protected K k4; /** */ protected V v4; /** * Constructs map. */ Map4() { // No-op. } /** * Constructs map. * * @param k1 Key1. * @param v1 Value1. * @param k2 Key2. * @param v2 Value2. * @param k3 Key3. * @param v3 Value3. * @param k4 Key4. * @param v4 Value4. */ Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { super(k1, v1, k2, v2, k3, v3); this.k4 = k4; this.v4 = v4; } /** {@inheritDoc} */ @Override public boolean isFull() { return size() == 4; } /** {@inheritDoc} */ @Nullable @Override public V remove(Object key) { if (F.eq(key, k4)) { V res = v4; v4 = null; k4 = null; return res; } return super.remove(key); } /** {@inheritDoc} */ @Override public int size() { return super.size() + (k4 != null ? 1 : 0); } /** {@inheritDoc} */ @Override public boolean containsKey(Object k) { return super.containsKey(k) || (k4 != null && F.eq(k, k4)); } /** {@inheritDoc} */ @Override public boolean containsValue(Object v) { return super.containsValue(v) || (k4 != null && F.eq(v, v4)); } /** {@inheritDoc} */ @Nullable @Override public V get(Object k) { V v = super.get(k); return v != null ? v : (k4 != null && F.eq(k, k4)) ? v4 : null; } /** * Puts key-value pair into map only if given key is already contained in the map * or there are free slots. * Note that this implementation of {@link Map#put(Object, Object)} does not match * general contract of {@link Map} interface and serves only for internal purposes. * * @param key Key. * @param val Value. * @return Previous value associated with given key. */ @Nullable @Override public V put(K key, V val) throws NullPointerException { V oldVal = get(key); if (k1 == null || F.eq(k1, key)) { k1 = key; v1 = val; } else if (k2 == null || F.eq(k2, key)) { k2 = key; v2 = val; } else if (k3 == null || F.eq(k3, key)) { k3 = key; v3 = val; } else if (k4 == null || F.eq(k4, key)) { k4 = key; v4 = val; } return oldVal; } /** {@inheritDoc} */ @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { private int idx; private Entry next; { if (k1 != null) { idx = 1; next = e(k1, v1); } else if (k2 != null) { idx = 2; next = e(k2, v2); } else if (k3 != null) { idx = 3; next = e(k3, v3); } else if (k4 != null) { idx = 4; next = e(k4, v4); } } @Override public boolean hasNext() { return next != null; } @SuppressWarnings("fallthrough") @Override public Entry next() { if (!hasNext()) throw new NoSuchElementException(); Entry old = next; next = null; switch (idx) { case 1: if (k2 != null) { idx = 2; next = e(k2, v2); break; } case 2: if (k3 != null) { idx = 3; next = e(k3, v3); break; } case 3: if (k4 != null) { idx = 4; next = e(k4, v4); break; } } return old; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return Map4.this.size(); } }; } } |
data class | Long class2 Long method3 Feature envy4 Inconsistent naming conventions5 Unnecessary comments6 Data class7 Frequent use of conditional statements and null checks8 Complex and convoluted code logic9 Violation of Liskov substitution principle (subclass Map4 does not strictly adhere to the behavior of its superclass Map3) | t | f | t | 0 | 13149 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/util/GridLeanMap.java/#L836-L1027 | 2 | 2097 | 13149 | ||
| 2098 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | data class, long method | t | t | t | long method | 0 | 13153 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 2098 | 13153 | |
| 2098 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Insufficient encapsulation 4. Inconsistent formatting 5. Use of magic numbers 6. Duplicate code 7. Inappropriate commenting 8. Inadequate naming 9. Lack of modularity 10. Underuse of abstractions 11. Frequent code changes 12. Poor exception handling 13. Lack of error checking 14. Mixing of concerns 15. Inappropriate levels of abstraction 16. Use of static method 17. Unused variables 18. Confusing variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | Long method2 Feature envy 3 Insufficient encapsulation 4 Inconsistent formatting 5 Use of magic numbers 6 Duplicate code 7 Inappropriate commenting 8 Inadequate naming 9 Lack of modularity | t | f | f | . Long method2. Feature envy 3. Insufficient encapsulation 4. Inconsistent formatting 5. Use of magic numbers 6. Duplicate code 7. Inappropriate commenting 8. Inadequate naming 9. Lack of modularity | data class | 0 | 13153 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 2098 | 13153 |
| 2099 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13157 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 2099 | 13157 |
| 2099 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13157 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 2099 | 13157 | ||
| 2100 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | 1. long method | t | t | f | long method | 0 | 13158 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 2100 | 13158 | |
| 2100 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Inconsistent indentation 5. Duplicate code 6. Inconsistent naming convention | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy3 Data class4 Inconsistent indentation5 Duplicate code6 Inconsistent naming convention | t | f | t | 0 | 13158 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 2100 | 13158 | ||
| 2101 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static String replaceSubstitution(String base, Pattern from, String to, boolean repeat) { Matcher match = from.matcher(base); if (repeat) { return match.replaceAll(to); } else { return match.replaceFirst(to); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13160 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KerberosName.java/#L287-L295 | 1 | 2101 | 13160 |
| 2101 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static String replaceSubstitution(String base, Pattern from, String to, boolean repeat) { Matcher match = from.matcher(base); if (repeat) { return match.replaceAll(to); } else { return match.replaceFirst(to); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13160 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KerberosName.java/#L287-L295 | 2 | 2101 | 13160 | ||
| 2102 | // bad smells are YES I found bad smells the bad smells are: 1. Hard coded values 2. Poor variable naming conventions (count, txid) 3. Public access modifiers for class and variable 4. No documentation or comments 5. No spacing or indentation 6. Underscore in class name 7. Incorrect indentation for class and variables 8. Inconsistent formatting 9. Unused import statement | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | Hard coded values 2 Poor variable naming conventions (count, txid) 3 Public access modifiers for class and variable 4 No documentation or comments 5 No spacing or indentation 6 Underscore in class name 7 Incorrect indentation for class and variables 8 Inconsistent formatting 9 Unused import statement | t | f | f | . Hard coded values 2. Poor variable naming conventions (count, txid) 3. Public access modifiers for class and variable 4. No documentation or comments 5. No spacing or indentation 6. Underscore in class name 7. Incorrect indentation for class and variables 8. Inconsistent formatting 9. Unused import statement | data class | 0 | 13161 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 2102 | 13161 |
| 2102 | { "response": "YES, I found bad smells", "detected_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | data class, long method | t | t | t | long method | 0 | 13161 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 2102 | 13161 | |
| 2103 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13166 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 1 | 2103 | 13166 |
| 2103 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 13166 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 2 | 2103 | 13166 |
| 2104 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smell": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | bad_smell: long method | t | t | f | long method | 0 | 13168 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 2104 | 13168 | |
| 2104 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | Long method | t | f | t | 0 | 13168 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 2104 | 13168 | ||
| 2105 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method | t | t | t | 0 | 13169 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 2105 | 13169 | ||
| 2105 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | Feature envy2 Long method | t | f | t | 0 | 13169 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 2105 | 13169 | ||
| 2107 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | 1. long method, 2. data class | t | t | f | 1. long method | data class | 0 | 13177 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 2107 | 13177 |
| 2107 | YES I found bad smells the bad smells are: 1. Duplication of code in the constructor for the fields authorizations, conf, useSample, and sampleConf. 2. Feature envy in the methods getTopLevelIterator and cloneWithSamplingEnabled, as they are manipulating the data of the iterator environment's fields instead of their own. 3. The use of deprecated methods, indicating that the code may need to be updated or refactored. 4. Long method with multiple responsibilities, as the class has both iterator environment related methods and methods for handling sampling and configuration. 5. Possible inconsistency in naming conventions for fields and methods (e.g. authorizations vs auths, topLevelIterators vs allIters). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Duplication of code in the constructor for the fields authorizations, conf, useSample, and sampleConf2 Feature envy in the methods getTopLevelIterator and cloneWithSamplingEnabled, as they are manipulating the data of the iterator environment's fields instead of their own3 The use of deprecated methods, indicating that the code may need to be updated or refactored4 Long method with multiple responsibilities, as the class has both iterator environment related methods and methods for handling sampling and configuration5 Possible inconsistency in naming conventions for fields and methods (eg authorizations vs auths, topLevelIterators vs allIters) | t | f | f | . Duplication of code in the constructor for the fields authorizations, conf, useSample, and sampleConf.2. Feature envy in the methods getTopLevelIterator and cloneWithSamplingEnabled, as they are manipulating the data of the iterator environment's fields instead of their own.3. The use of deprecated methods, indicating that the code may need to be updated or refactored.4. Long method with multiple responsibilities, as the class has both iterator environment related methods and methods for handling sampling and configuration.5. Possible inconsistency in naming conventions for fields and methods (e.g. authorizations vs auths, topLevelIterators vs allIters). | data class | 0 | 13177 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 2107 | 13177 |
| 2109 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Not specified | f | f | f | false | 0 | 13180 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 2109 | 13180 | |
| 2109 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | f | f | f | data class | 0 | 13180 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 2109 | 13180 | ||
| 2110 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | long method | t | t | t | 0 | 13182 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 2110 | 13182 | ||
| 2110 | YES I found bad smellsthe bad smells are: 1. Long method 2. Repeated code (sentryClient.grantRoleToGroups() and sentryClient.revokeRoleFromGroups()) 3. Mixing of concerns (roles and groups being handled in the same method) 4. Lack of proper error handling (catch block does not handle all types of exceptions) 5. Inconsistent naming conventions (camel case and underscore usage) 6. Using generic exception types instead of specific ones 7. Lack of comments/documentation to explain the purpose of the code and its functionality. 8. Nested try-catch blocks 9. Tight coupling (dependency on specific implementation of SentryClient) 10. Code duplication (grant/revoke functionality is repeated for each role) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Repeated code (sentryClientgrantRoleToGroups() and sentryClientrevokeRoleFromGroups())3 Mixing of concerns (roles and groups being handled in the same method)4 Lack of proper error handling (catch block does not handle all types of exceptions)5 Inconsistent naming conventions (camel case and underscore usage)6 Using generic exception types instead of specific ones7 Lack of comments/documentation to explain the purpose of the code and its functionality8 Nested try-catch blocks9 Tight coupling (dependency on specific implementation of SentryClient) | t | f | t | 0 | 13182 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 2110 | 13182 | ||
| 2111 | {"message": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13188 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 1 | 2111 | 13188 |
| 2111 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13188 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 2 | 2111 | 13188 | ||
| 2112 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13189 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 2112 | 13189 | |
| 2112 | YES I found bad smells The bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Magic numbers 5. Confusing variable names 6. Lack of comments/documentation 7. Use of nested conditional statements 8. Use of multiple unnecessary checks and comparisons 9. Inefficient if-else structure | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method2 Repeated code3 Feature envy4 Magic numbers5 Confusing variable names6 Lack of comments/documentation7 Use of nested conditional statements8 Use of multiple unnecessary checks and comparisons 9 Inefficient if-else structure | t | f | t | 0 | 13189 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 2112 | 13189 | ||
| 2113 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | long method | t | t | f | long method | data class | 0 | 13191 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 1 | 2113 | 13191 |
| 2113 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy (related to the MouseAdapter and MouseMoveListener) 3. Duplicate code (there are several sections of code that have very similar functions but are repeated) 4. Magic numbers (hard-coded numbers like 1, 2, 16, etc. which should be stored as constants for better readability) 5. Primitive obsession (the use of primitive data types instead of creating a separate class or object) 6. Inconsistent naming conventions (some variable names are camelCase while others are not) 7. Complex if-else statements (the if-else structure is convoluted and could be simplified) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | Long method2 Feature envy (related to the MouseAdapter and MouseMoveListener)3 Duplicate code (there are several sections of code that have very similar functions but are repeated)4 Magic numbers (hard-coded numbers like | t | f | f | . Long method2. Feature envy (related to the MouseAdapter and MouseMoveListener)3. Duplicate code (there are several sections of code that have very similar functions but are repeated)4. Magic numbers (hard-coded numbers like | data class | 0 | 13191 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 2 | 2113 | 13191 |
| 2115 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method, data class | t | t | t | data class | 0 | 13193 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 2115 | 13193 | |
| 2115 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13193 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 2115 | 13193 | ||
| 2117 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | 1. long method | t | t | t | 0 | 13197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 2117 | 13197 | ||
| 2117 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Comments 4. Magic numbers 5. Use of raw types | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Feature envy 2 Long method 3 Comments 4 Magic numbers 5 Use of raw types | t | f | t | 0 | 13197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 2117 | 13197 | ||
| 2118 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13199 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 1 | 2118 | 13199 |
| 2118 | YES I found bad smells the bad smells are: 1. Short method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | Short method2 Feature envy | t | f | t | 0 | 13199 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 2 | 2118 | 13199 | ||
| 2122 | YES I found bad smells the bad smells are: 1. Long method (createLuceneListenersAndFileChunkRegions) 2. Feature envy (isIndexingInProgress) 3. Feature envy (createRegion) 4. Duplicated code (createRegion) 5. Primitive obsession (createRegion) 6. Long method (createRegion) 7. Long parameter list (configureLuceneRegionAttributesFactory) 8. Long method (isIndexAvailable) 9. Magic numbers (LuceneServiceImpl.LUCENE_REINDEX) 10. Long method (destroy) 11. Large class (LuceneIndexForPartitionedRegion) 12. Lazy class (LuceneIndexForPartitionedRegion) 13. Long method (destroyOnRemoteMembers) 14. Message chains (getDataRegion().getDistributionManager()) 15. Long method (waitForReplies) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
data class | Long method (createLuceneListenersAndFileChunkRegions)2 Feature envy (isIndexingInProgress)3 Feature envy (createRegion)4 Duplicated code (createRegion)5 Primitive obsession (createRegion)6 Long method (createRegion)7 Long parameter list (configureLuceneRegionAttributesFactory)8 Long method (isIndexAvailable)9 Magic numbers (LuceneServiceImplLUCENE_REINDEX) | t | f | f | . Long method (createLuceneListenersAndFileChunkRegions)2. Feature envy (isIndexingInProgress)3. Feature envy (createRegion)4. Duplicated code (createRegion)5. Primitive obsession (createRegion)6. Long method (createRegion)7. Long parameter list (configureLuceneRegionAttributesFactory)8. Long method (isIndexAvailable)9. Magic numbers (LuceneServiceImpl.LUCENE_REINDEX) | data class | 0 | 13214 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 2 | 2122 | 13214 |
| 2124 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 13216 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 1 | 2124 | 13216 |
| 2124 | YES I found bad smells the bad smells are: 1. Feature envy - TextAndButtonSection class is calling methods and accessing properties of other classes too frequently. 2. Long method - Some methods in the TextAndButtonSection class are longer than they should be, making the code harder to read and maintain. 3. Primitive obsession - Primitive data types such as int and boolean are used instead of creating specific classes for them. 4. Commented out code - There are several lines of code that have been commented out, indicating that they may have been used at one point but are no longer needed. 5. Data clump - Several properties such as buttonText, buttonTooltipText, and buttonWidth are all related to the same GUI element (the button), but are declared separately instead of being grouped together. 6. Inconsistent naming - Some variables and methods use camelCase while others use snake_case. 7. Unnecessary boolean checks - In the createSection() method, the condition in the if statement is always true, making it unnecessary to check it. 8. Unused variables - Several variables, such as oldValue and provider, are declared but not used anywhere in the code. 9. Magic numbers - Some numbers, such as -1 and 0, are used as parameters or compared to, but their purpose or significance is not clear. 10. Complex code - Some methods have complex calculations and logic that could be simplified and made more readable. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | Feature envy - TextAndButtonSection class is calling methods and accessing properties of other classes too frequently2 Long method - Some methods in the TextAndButtonSection class are longer than they should be, making the code harder to read and maintain3 Primitive obsession - Primitive data types such as int and boolean are used instead of creating specific classes for them4 Commented out code - There are several lines of code that have been commented out, indicating that they may have been used at one point but are no longer needed5 Data clump - Several properties such as buttonText, buttonTooltipText, and buttonWidth are all related to the same GUI element (the button), but are declared separately instead of being grouped together6 Inconsistent naming - Some variables and methods use camelCase while others use snake_case7 Unnecessary boolean checks - In the createSection() method, the condition in the if statement is always true, making it unnecessary to check it8 Unused variables - Several variables, such as oldValue and provider, are declared but not used anywhere in the code9 Magic numbers - Some numbers, such as - | t | f | f | . Feature envy - TextAndButtonSection class is calling methods and accessing properties of other classes too frequently.2. Long method - Some methods in the TextAndButtonSection class are longer than they should be, making the code harder to read and maintain.3. Primitive obsession - Primitive data types such as int and boolean are used instead of creating specific classes for them.4. Commented out code - There are several lines of code that have been commented out, indicating that they may have been used at one point but are no longer needed.5. Data clump - Several properties such as buttonText, buttonTooltipText, and buttonWidth are all related to the same GUI element (the button), but are declared separately instead of being grouped together.6. Inconsistent naming - Some variables and methods use camelCase while others use snake_case.7. Unnecessary boolean checks - In the createSection() method, the condition in the if statement is always true, making it unnecessary to check it.8. Unused variables - Several variables, such as oldValue and provider, are declared but not used anywhere in the code.9. Magic numbers - Some numbers, such as - | data class | 0 | 13216 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 2 | 2124 | 13216 |
| 2126 | {"message": "YES, I found bad smells.", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | data class | t | t | t | 0 | 13221 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 2126 | 13221 | ||
| 2126 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | f | f | f | data class | 0 | 13221 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 2126 | 13221 | ||
| 2127 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 13223 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 2127 | 13223 | ||
| 2127 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13223 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 2127 | 13223 | ||
| 2128 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13224 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 2128 | 13224 |
| 2128 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13224 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 2128 | 13224 | ||
| 2130 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13230 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 2130 | 13230 | ||
| 2131 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | long method, data class | t | t | t | data class | 0 | 13232 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 2131 | 13232 | |
| 2131 | YES I found bad smells the bad smells are: 1. Duplicate code (creating multiple nodes) 2. Long method (contains multiple operations) 3. Feature envy (NodeManager.add method being used frequently) 4. Primitive obsession (defining variable types as double and integer instead of creating custom objects) 5. Catch and hide exception (no proper handling of the exception) 6. Lack of readability and organization, making it difficult to understand the flow of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | Duplicate code (creating multiple nodes)2 Long method (contains multiple operations)3 Feature envy (NodeManageradd method being used frequently)4 Primitive obsession (defining variable types as double and integer instead of creating custom objects)5 Catch and hide exception (no proper handling of the exception)6 Lack of readability and organization, making it difficult to understand the flow of the code | t | f | t | making it difficult to understand the flow of the code. | 0 | 13232 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 2131 | 13232 | |
| 2132 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | long method | t | t | t | 0 | 13234 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 2132 | 13234 | ||
| 2132 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 13234 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 2132 | 13234 | |
| 2133 | {"message": "YES I found bad smells the bad smells are:", "bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 13238 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 1 | 2133 | 13238 | |
| 2133 | SequenceFileReader YES, I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Conditional complexity 4. Feature envy 5. Inconsistent formatting 6. Confusing variable names 7. Lack of encapsulation 8. Empty catch block 9. Incomplete error handling 10. Inconsistent commenting 11. Long parameter list 12. Cluttered and unorganized code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | Long method2 Duplicate code3 Conditional complexity4 Feature envy5 Inconsistent formatting6 Confusing variable names7 Lack of encapsulation8 Empty catch block9 Incomplete error handling | t | f | f | . Long method2. Duplicate code3. Conditional complexity4. Feature envy5. Inconsistent formatting6. Confusing variable names7. Lack of encapsulation8. Empty catch block9. Incomplete error handling | data class | 0 | 13238 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 2 | 2133 | 13238 |
| 2135 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method | t | t | t | 0 | 13243 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2135 | 13243 | ||
| 2135 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Shotgun surgery, 4. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method, 2 Feature envy, 3 Shotgun surgery, 4 Duplicate code | t | f | t | 2. Feature envy, 3. Shotgun surgery, 4. Duplicate code | 0 | 13243 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2135 | 13243 | |
| 2137 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | data class | t | t | t | 0 | 13258 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 1 | 2137 | 13258 | ||
| 2137 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13258 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 2 | 2137 | 13258 |
| 2138 | after setting up and validating the experiment. * * * * @param airavataExperiment * @return The Experiment * @throws org.apache.airavata.registry.api.exception.RegistryServiceException */APPLICATION_LOGIC, YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method2 Feature envy | t | f | t | 0 | 13259 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 2138 | 13259 | ||
| 2138 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 13259 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 2138 | 13259 |
| 2139 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | data class | t | t | t | 0 | 13262 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 1 | 2139 | 13262 | ||
| 2139 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 13262 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 2 | 2139 | 13262 |
| 2140 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | data class | t | t | t | 0 | 13264 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 1 | 2140 | 13264 | ||
| 2140 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13264 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 2 | 2140 | 13264 |
| 2141 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | data class, long method | t | t | t | long method | 0 | 13266 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 2141 | 13266 | |
| 2141 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13266 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 2 | 2141 | 13266 |
| 2142 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | long method | t | t | f | long method | data class | 0 | 13268 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 1 | 2142 | 13268 |
| 2142 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13268 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 2 | 2142 | 13268 |
| 2145 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 13274 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 1 | 2145 | 13274 |
| 2145 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | Feature envy | t | f | t | 0 | 13274 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 2 | 2145 | 13274 | ||
| 2146 | {"response": "YES, I found bad smells. The bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | 1. data class | t | t | f | data class | 0 | 13275 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 2146 | 13275 | |
| 2146 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13275 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 2146 | 13275 |
| 2147 | {"error": "Sorry, I am unable to provide direct code analysis or execution. However, I can help guide you on how to identify common code smells in Java code by providing descriptions and examples. Let me know if you need any information."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | f | f | f | data class | 0 | 13277 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 1 | 2147 | 13277 | ||
| 2147 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 13277 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 2 | 2147 | 13277 |
| 2148 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Not specified | f | f | f | false | 0 | 13280 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 2148 | 13280 | |
| 2148 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 13280 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 2148 | 13280 | |
| 2149 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method | t | t | t | 0 | 13283 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 2149 | 13283 | ||
| 2149 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Feature envy, 2Long method | t | f | t | .Feature envy | 0 | 13283 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 2149 | 13283 | |
| 2150 | {"message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13287 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 2150 | 13287 |
| 2150 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | data class | 0 | 13287 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 2150 | 13287 |
| 2152 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13294 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 2152 | 13294 |
| 2153 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method | t | t | t | 0 | 13295 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 2153 | 13295 | ||
| 2153 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Mix of responsibilities (method is responsible for too many things) 4. Inconsistent formatting and naming conventions 5. Arbitrary integer value used without clear explanation or justification 6. Nested if statements 7. Use of null values 8. Use of raw data types instead of object-oriented approach 9. Potential for null pointer exception 10. Potential for index out of bounds exception 11. Magic numbers/strings used (e.g. 0, "0") 12. Violation of the Single Responsibility Principle (SRP) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method2 Duplicate code3 Mix of responsibilities (method is responsible for too many things)4 Inconsistent formatting and naming conventions5 Arbitrary integer value used without clear explanation or justification6 Nested if statements7 Use of null values8 Use of raw data types instead of object-oriented approach9 Potential for null pointer exception | t | f | t | 0 | 13295 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 2153 | 13295 | ||
| 2154 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 13296 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 2154 | 13296 |
| 2154 | YES, I found bad smells the bad smells are:1. Long method, 2. Primitive obsession, 3. Duplicate code, 4. Magic number (0), 5. Feature envy, 6. Inappropriate commenting, 7. Inconsistent formatting, 8. Data clumps, 9. Missing abstraction, 10. Inefficient looping (for loop instead of foreach), 11. Inappropriate use of List (instead of Set or Map). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
feature envy | Long method, 2 Primitive obsession, 3 Duplicate code, 4 Magic number (0), 5 Feature envy, 6 Inappropriate commenting, 7 Inconsistent formatting, 8 Data clumps, 9 Missing abstraction, | t | f | t | . Long method, 2. Primitive obsession, 3. Duplicate code, 4. Magic number (0), 6. Inappropriate commenting, 7. Inconsistent formatting, 8. Data clumps, 9. Missing abstraction, | 0 | 13296 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 2154 | 13296 | |
| 2155 | YES I found bad smells the bad smells are: 1. Long method 2. Code duplication 3. Magic numbers 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | Long method2 Code duplication3 Magic numbers4 Feature envy | t | f | f | . Long method2. Code duplication3. Magic numbers4. Feature envy | data class | 0 | 13299 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 2 | 2155 | 13299 |
| 2156 | {"message": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | 1. long method | t | t | f | long method | 0 | 13302 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 2156 | 13302 | |
| 2156 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13302 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2156 | 13302 | ||
| 2157 | { "output": "YES I found bad smells", "bad smells are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | feature envy | t | t | f | feature envy | long method | 0 | 13311 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 2157 | 13311 |
| 2157 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inconsistent formatting 6. Poor naming conventions 7. Inadequate commenting 8. Inefficient use of conditional statements 9. Inefficient use of variables 10. Poor use of class hierarchy 11. Mixing of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method2 Feature envy 3 Duplicate code 4 Magic numbers 5 Inconsistent formatting 6 Poor naming conventions 7 Inadequate commenting 8 Inefficient use of conditional statements 9 Inefficient use of variables | t | f | t | 0 | 13311 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 2157 | 13311 | ||
| 2158 | { "message": "YES I found bad smells. the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 13316 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 | 1 | 2158 | 13316 | |
| 2158 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13316 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 | 2 | 2158 | 13316 |
| 2159 | {"response": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | data class | t | t | t | 0 | 13318 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 1 | 2159 | 13318 | ||
| 2159 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13318 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 2 | 2159 | 13318 |
| 2160 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13321 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 2160 | 13321 |
| 2160 | YES I found bad smells 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13321 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 2160 | 13321 |
| 2161 | { "response": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13324 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 2161 | 13324 |
| 2161 | YES I found bad smells The bad smells are: 1. Long class - The class has a lot of different methods, which can indicate that it is trying to do too many things and may not be focused on a specific purpose. 2. Long parameter list - The constructor for the TupleImpl class has 5 parameters, which can be a sign that the class is trying to do too much and may be violating the Single Responsibility Principle. 3. Feature envy - The TupleImpl class accesses and uses fields and methods from the GeneralTopologyContext class frequently, which can indicate that the class is more interested in the data of other classes rather than its own data. 4. Too many getters and setters - The TupleImpl class has several methods for setting and getting different values, which can indicate that the class is not properly encapsulating its data and may lead to data exposure or modification. 5. Comments - The code contains commented out code, which can indicate that the code is not properly maintained and increases the overall size of the code base. 6. Nested classes - The code contains several nested classes within the TupleImpl class, which can make the code more complex and difficult to understand. 7. Magic numbers - The code contains several hardcoded numbers, such as 0, 1, and 2, which can make the code less readable and may lead to errors if the numbers are changed in the future. 8. Similar methods - The TupleImpl class has several methods that perform similar actions, such as getString(), getInteger(), getLong(), etc. This can indicate that the class may not be well-designed and may benefit from refactoring. 9. Poor naming conventions - Some of the variable names, such as _map and _meta, do not follow standard naming conventions and may be confusing for other developers to understand. 10. Direct object manipulation - The code directly accesses and modifies object data, which can violate the principles of proper object-oriented programming. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | Long class - The class has a lot of different methods, which can indicate that it is trying to do too many things and may not be focused on a specific purpose2 Long parameter list - The constructor for the TupleImpl class has 5 parameters, which can be a sign that the class is trying to do too much and may be violating the Single Responsibility Principle3 Feature envy - The TupleImpl class accesses and uses fields and methods from the GeneralTopologyContext class frequently, which can indicate that the class is more interested in the data of other classes rather than its own data4 Too many getters and setters - The TupleImpl class has several methods for setting and getting different values, which can indicate that the class is not properly encapsulating its data and may lead to data exposure or modification5 Comments - The code contains commented out code, which can indicate that the code is not properly maintained and increases the overall size of the code base6 Nested classes - The code contains several nested classes within the TupleImpl class, which can make the code more complex and difficult to understand7 Magic numbers - The code contains several hardcoded numbers, such as 0, | t | f | f | . Long class - The class has a lot of different methods, which can indicate that it is trying to do too many things and may not be focused on a specific purpose.2. Long parameter list - The constructor for the TupleImpl class has 5 parameters, which can be a sign that the class is trying to do too much and may be violating the Single Responsibility Principle.3. Feature envy - The TupleImpl class accesses and uses fields and methods from the GeneralTopologyContext class frequently, which can indicate that the class is more interested in the data of other classes rather than its own data.4. Too many getters and setters - The TupleImpl class has several methods for setting and getting different values, which can indicate that the class is not properly encapsulating its data and may lead to data exposure or modification.5. Comments - The code contains commented out code, which can indicate that the code is not properly maintained and increases the overall size of the code base.6. Nested classes - The code contains several nested classes within the TupleImpl class, which can make the code more complex and difficult to understand.7. Magic numbers - The code contains several hardcoded numbers, such as 0, | data class | 0 | 13324 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 2161 | 13324 |
| 2163 | { "message": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | long method | t | t | f | long method | data class | 0 | 13330 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 2163 | 13330 |
| 2163 | YES, I found bad smells. the bad smells are: 1. Large class, 2. Long method, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Large class, 2 Long method, 3 Feature envy | t | f | f | . Large class, 2. Long method, 3. Feature envy | data class | 0 | 13330 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 2163 | 13330 |
| 2164 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | long method | t | t | t | 0 | 13339 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 2164 | 13339 | ||
| 2164 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13339 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 2164 | 13339 | ||
| 2165 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2165 | 13347 |
| 2165 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2165 | 13347 | ||
| 2166 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | long method | t | t | t | 0 | 13348 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2166 | 13348 | ||
| 2166 | Yes, I found bad smells(the bad smells are: 1. Long method 2. Data class 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method2 Data class3 Feature envy | t | f | t | 0 | 13348 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2166 | 13348 | ||
| 2167 | { "response": "YES I found bad smells", "the bad smells are:": [ "Long method", "Duplicate code" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | long method, duplicate code | t | t | f | long method, duplicate code | data class | 0 | 13349 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 2 | 2167 | 13349 |
| 2168 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Not specified | f | f | f | false | 0 | 13354 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 2168 | 13354 | |
| 2168 | YES I found bad smells The bad smells are: 1. Long method 2. Redundant code 3. Feature envy 4. Comments to state the obvious 5. Magic numbers 6. Inconsistent naming conventions 7. Inconsistent formatting 8. Poor exception handling 9. Code duplication with slight variations | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method 2 Redundant code3 Feature envy4 Comments to state the obvious 5 Magic numbers 6 Inconsistent naming conventions 7 Inconsistent formatting 8 Poor exception handling 9 Code duplication with slight variations | t | f | t | 0 | 13354 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 2168 | 13354 | ||
| 2170 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
data class | data class, long method | t | t | t | long method | 0 | 13356 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 2170 | 13356 | |
| 2171 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ManagedAttributeValueType public interface AclRule extends ManagedAttributeValue { String getIdentity(); ObjectType getObjectType(); LegacyOperation getOperation(); Map getAttributes(); RuleOutcome getOutcome(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13382 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AclRule.java/#L31-L39 | 2 | 2171 | 13382 |
| 2172 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | long method | t | t | f | long method | data class | 0 | 13384 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 1 | 2172 | 13384 |
| 2172 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13384 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 2 | 2172 | 13384 |
| 2173 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13386 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 1 | 2173 | 13386 |
| 2173 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13386 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 2 | 2173 | 13386 |
| 2175 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | data class, long method | t | t | t | long method | 0 | 13394 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 2175 | 13394 | |
| 2175 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate Code 4. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | Long method 2 Feature envy 3 Duplicate Code 4 Inappropriate Intimacy | t | f | f | . Long method 2. Feature envy 3. Duplicate Code 4. Inappropriate Intimacy | data class | 0 | 13394 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 2175 | 13394 |
| 2176 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | data class | t | t | t | 0 | 13404 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 2176 | 13404 | ||
| 2176 | YES, I found bad smells. 1. Long method, 2. Feature envy. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long method, 2 Feature envythe bad smells are: | t | f | f | . Long method, 2. Feature envy.the bad smells are: | data class | 0 | 13404 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 2176 | 13404 |
| 2177 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | 1. long method | t | t | t | 0 | 13408 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 2177 | 13408 | ||
| 2177 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 13408 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 2177 | 13408 | ||
| 2178 | { "response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | data class, long method | t | t | t | long method | 0 | 13410 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 1 | 2178 | 13410 | |
| 2178 | "Yes I found bad smells" The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 13410 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 2 | 2178 | 13410 |
| 2179 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 13412 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 1 | 2179 | 13412 | ||
| 2179 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 13412 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 2 | 2179 | 13412 |
| 2180 | { "message": "YES I found bad smells", "bad_smells": [ { "smell": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | smell: long method | t | t | t | 0 | 13413 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 2180 | 13413 | ||
| 2180 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13413 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 2180 | 13413 | ||
| 2181 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | long method, data class | t | t | t | long method | 0 | 13416 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 1 | 2181 | 13416 | |
| 2181 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13416 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 2 | 2181 | 13416 |
| 2182 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | data class | t | t | t | 0 | 13420 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 1 | 2182 | 13420 | ||
| 2182 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: The class is extending a different class and implementing an interface, which may indicate a potential violation of the Single Responsibility Principle (SRP). 3. Redundant code: The private field "KapuaId accessInfo" and its corresponding getter/setter methods are not being used anywhere in the class. 4. Magic number: The serialVersionUID value is a hardcoded number and may be difficult to understand or maintain in the future. 5. Inconsistent naming: The class is named "AccessRoleCreatorImpl", but it is extending a different class called "AbstractKapuaEntityCreator". This may cause confusion for other developers. 6. Unused constructor parameter: The constructor has a parameter for "scopeId", but it is not being used anywhere in the constructor or class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Long method2 Feature envy: The class is extending a different class and implementing an interface, which may indicate a potential violation of the Single Responsibility Principle (SRP)3 Redundant code: The private field "KapuaId accessInfo" and its corresponding getter/setter methods are not being used anywhere in the class4 Magic number: The serialVersionUID value is a hardcoded number and may be difficult to understand or maintain in the future5 Inconsistent naming: The class is named "AccessRoleCreatorImpl", but it is extending a different class called "AbstractKapuaEntityCreator" This may cause confusion for other developers 6 Unused constructor parameter: The constructor has a parameter for "scopeId", but it is not being used anywhere in the constructor or class | t | f | f | . Long method2. Feature envy: The class is extending a different class and implementing an interface, which may indicate a potential violation of the Single Responsibility Principle (SRP).3. Redundant code: The private field "KapuaId accessInfo" and its corresponding getter/setter methods are not being used anywhere in the class.4. Magic number: The serialVersionUID value is a hardcoded number and may be difficult to understand or maintain in the future.5. Inconsistent naming: The class is named "AccessRoleCreatorImpl", but it is extending a different class called "AbstractKapuaEntityCreator". This may cause confusion for other developers. 6. Unused constructor parameter: The constructor has a parameter for "scopeId", but it is not being used anywhere in the constructor or class. | data class | 0 | 13420 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 2 | 2182 | 13420 |
| 2183 | YES I found bad smells, Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | t | f | f | data class | 0 | 13424 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 2 | 2183 | 13424 | ||
| 2184 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13426 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 2 | 2184 | 13426 |
| 2185 | YES I found bad smells the bad smells are: Long method, Duplicated code, Complex code, Feature envy, Inconsistent naming convention, Unnecessary comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method,Duplicated code,Complex code,Feature envy,Inconsistent naming convention,Unnecessary comments | t | f | t | Duplicated code, Complex code, Feature envy, Inconsistent naming convention, Unnecessary comments. | 0 | 13430 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 2185 | 13430 | |
| 2186 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13435 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 1 | 2186 | 13435 |
| 2186 | YES I found bad smells The bad smells are: 1. Large Class, 2. Large Method, 3. Data Class, 4. Long Parameter List | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | Large Class, 2 Large Method, 3 Data Class, 4 Long Parameter List | t | f | t | . Large Class, 2. Large Method, 4. Long Parameter List | 0 | 13435 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 2 | 2186 | 13435 | |
| 2187 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | data class | t | t | t | 0 | 13438 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 1 | 2187 | 13438 | ||
| 2187 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13438 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 2 | 2187 | 13438 |
| 2188 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 13444 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 2188 | 13444 | |
| 2189 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "The 'Statement' class contains multiple methods that can be considered long." } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | 1. long method: the statement class contains multiple methods that can be considered long. | t | t | f | 1. long method: the statement class contains multiple methods that can be considered long. | data class | 0 | 13450 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 1 | 2189 | 13450 |
| 2189 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13450 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 2 | 2189 | 13450 |
| 2190 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 13458 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 2 | 2190 | 13458 |
| 2191 | { "output": "YES I found bad smells", "detectedBadSmells": [ { "bad smells are": [ "Data Class", "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
data class | bad smells are: data class, long method | t | t | t | long method | 0 | 13466 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 1 | 2191 | 13466 | |
| 2191 | {"response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13466 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 2 | 2191 | 13466 |
| 2192 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13474 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 2 | 2192 | 13474 |
| 2193 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 13477 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 1 | 2193 | 13477 | |
| 2193 | YES, I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13477 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 2 | 2193 | 13477 | ||
| 2196 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } } |
data class | data class, long method | t | t | t | long method | 0 | 13481 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 | 1 | 2196 | 13481 | |
| 2196 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13481 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 | 2 | 2196 | 13481 |
| 2197 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | long method | t | t | t | 0 | 13483 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 1 | 2197 | 13483 | ||
| 2197 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13483 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 2 | 2197 | 13483 | ||
| 2198 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | the bad smells are: long method | t | t | t | 0 | 13492 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2198 | 13492 | ||
| 2198 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Lack of proper error handling 5. Excessive amount of parameters 6. Excessive commenting 7. Lack of proper abstraction 8. Use of primitive types instead of objects 9. Inconsistent naming conventions 10. Excessive code duplication or repetition | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method 2 Feature envy 3 Nested loops 4 Lack of proper error handling 5 Excessive amount of parameters 6 Excessive commenting 7 Lack of proper abstraction 8 Use of primitive types instead of objects 9 Inconsistent naming conventions | t | f | t | 0 | 13492 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2198 | 13492 | ||
| 2199 | { "answer": "YES I found bad smells", "bad_smells": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | data class, long method | t | t | t | long method | 0 | 13495 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2199 | 13495 | |
| 2199 | of the code above. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 13495 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2199 | 13495 | ||
| 2200 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13500 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 1 | 2200 | 13500 |
| 2200 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13500 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 2 | 2200 | 13500 |
| 2201 | { "answer": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | the bad smells are: data class | t | t | t | 0 | 13502 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 2201 | 13502 | ||
| 2201 | { private int[][] data; public ArrayImageSource( int[][] data ) { super( data[ 0 ].length, data.length ); this.data = data; YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 13502 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 2201 | 13502 |
| 2203 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | long method, data class | t | t | t | data class | 0 | 13507 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 2203 | 13507 | |
| 2203 | YES, I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 13507 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 2203 | 13507 | ||
| 2204 | { "response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13510 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 1 | 2204 | 13510 |
| 2204 | YES, I found bad smells the bad smells are: 1. Long method 2. Repeated code 3. Constructor overloading with similar functionality 4. Lack of comments/documentation 5. Primitive obsession (using primitive types instead of creating a separate object) 6. Low cohesion (no common purpose or functionality in the class) 7. Poor naming conventions (unclear or generic names for variables and methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | Long method2 Repeated code3 Constructor overloading with similar functionality4 Lack of comments/documentation5 Primitive obsession (using primitive types instead of creating a separate object)6 Low cohesion (no common purpose or functionality in the class)7 Poor naming conventions (unclear or generic names for variables and methods) | t | f | f | . Long method2. Repeated code3. Constructor overloading with similar functionality4. Lack of comments/documentation5. Primitive obsession (using primitive types instead of creating a separate object)6. Low cohesion (no common purpose or functionality in the class)7. Poor naming conventions (unclear or generic names for variables and methods) | data class | 0 | 13510 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 2 | 2204 | 13510 |
| 2207 | { "output": "YES I found bad smells. The bad smells are: 1. Long method" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13515 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 2 | 2207 | 13515 |
| 2207 | {"YES I found bad smells":true,"the bad smells are:":["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13515 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 2207 | 13515 |
| 2209 | { "response": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | data class | t | t | t | 0 | 13518 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 1 | 2209 | 13518 | ||
| 2209 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13518 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 2 | 2209 | 13518 |
| 2212 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | data class, long method | t | t | t | long method | 0 | 13524 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 1 | 2212 | 13524 | |
| 2212 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13524 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 2 | 2212 | 13524 |
| 2213 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 13526 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 1 | 2213 | 13526 | ||
| 2213 | YES, I found bad smellsthe bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13526 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 2 | 2213 | 13526 |
| 2214 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | data class | t | t | t | 0 | 13528 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 1 | 2214 | 13528 | ||
| 2214 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13528 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 2 | 2214 | 13528 |
| 2215 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 13529 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 2 | 2215 | 13529 |
| 2216 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | data class | t | t | t | 0 | 13536 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 1 | 2216 | 13536 | ||
| 2216 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13536 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 2 | 2216 | 13536 |
| 2217 | {"message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | long method, data class | t | t | t | data class | 0 | 13539 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 2217 | 13539 | |
| 2217 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Long method 3. Feature envy 4. Switch statement 5. Magic numbers 6. Improper exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Duplicate code2 Long method 3 Feature envy4 Switch statement 5 Magic numbers 6 Improper exception handling | t | f | t | 0 | 13539 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 2217 | 13539 | ||
| 2218 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | 1. data class | t | t | t | 0 | 13542 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 1 | 2218 | 13542 | ||
| 2218 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13542 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 2 | 2218 | 13542 |
| 2219 | {"message":"YES, I found bad smells","bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
data class | data class | t | t | t | 0 | 13545 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 1 | 2219 | 13545 | ||
| 2220 | { "message": "YES I found bad smells, the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | 1. data class | t | t | t | 0 | 13551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 2220 | 13551 | ||
| 2220 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 2220 | 13551 |
| 2221 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13553 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 2221 | 13553 | |
| 2221 | Yes I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy | t | f | t | 0 | 13553 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 2221 | 13553 | ||
| 2222 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | data class | t | t | t | 0 | 13559 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 1 | 2222 | 13559 | ||
| 2222 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13559 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 2 | 2222 | 13559 |
| 2224 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | data class | t | t | t | 0 | 13570 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 1 | 2224 | 13570 | ||
| 2224 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13570 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 2 | 2224 | 13570 |
| 2225 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | \n1. data class | t | t | t | 0 | 13573 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 1 | 2225 | 13573 | ||
| 2225 | YES I found bad smells the bad smells are: 1. Meaningless comments, 2. DirectOwnership | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | Meaningless comments, 2 DirectOwnership | t | f | f | . Meaningless comments, 2. DirectOwnership | data class | 0 | 13573 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 2225 | 13573 |
| 2226 | YES I found bad smells the bad smells are: 1. Duplicate code (in the getEncodedKey and getEncodedValue methods). 2. Feature envy (The Header class is too focused on the key and value properties, which should instead be encapsulated in a separate class). 3. Poor naming conventions (the variable names "key" and "val" are not descriptive). 4. Inconsistent formatting and spacing (lack of indentation and inconsistent placement of brackets). 5. Lack of comments or documentation (no explanation of the purpose or functionality of the code). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | Duplicate code (in the getEncodedKey and getEncodedValue methods)2 Feature envy (The Header class is too focused on the key and value properties, which should instead be encapsulated in a separate class)3 Poor naming conventions (the variable names "key" and "val" are not descriptive)4 Inconsistent formatting and spacing (lack of indentation and inconsistent placement of brackets)5 Lack of comments or documentation (no explanation of the purpose or functionality of the code) | t | f | f | . Duplicate code (in the getEncodedKey and getEncodedValue methods).2. Feature envy (The Header class is too focused on the key and value properties, which should instead be encapsulated in a separate class).3. Poor naming conventions (the variable names "key" and "val" are not descriptive).4. Inconsistent formatting and spacing (lack of indentation and inconsistent placement of brackets).5. Lack of comments or documentation (no explanation of the purpose or functionality of the code). | data class | 0 | 13576 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 2 | 2226 | 13576 |
| 2227 | {"output": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | long method, data class | t | t | t | long method | 0 | 13578 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 2227 | 13578 | |
| 2227 | YES I found bad smells the bad smells are: 1. Long method 2. Data Clumps | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Long method2 Data Clumps | t | f | f | . Long method2. Data Clumps | data class | 0 | 13578 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 2227 | 13578 |
| 2228 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | 1. data class | t | t | t | 0 | 13581 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 1 | 2228 | 13581 | ||
| 2228 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 13581 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 2 | 2228 | 13581 |
| 2230 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13584 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 2230 | 13584 |
| 2230 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | data class, long method | t | t | t | long method | 0 | 13584 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 2230 | 13584 | |
| 2232 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | 1. data class | t | t | t | 0 | 13594 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 2232 | 13594 | ||
| 2232 | YES, I found bad smells. The bad smells are: Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Feature envy | t | f | f | Feature envy. | data class | 0 | 13594 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 2232 | 13594 |
| 2233 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 13595 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 1 | 2233 | 13595 | ||
| 2233 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13595 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 2 | 2233 | 13595 |
| 2235 | {"output": "YES I found bad smells. the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13609 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 1 | 2235 | 13609 |
| 2235 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13609 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 2 | 2235 | 13609 | ||
| 2236 | { "answer": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
long method | 1. long method | t | t | t | 0 | 13611 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 2236 | 13611 | ||
| 2236 | */ NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
long method | f | f | f | long method | 0 | 13611 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 2 | 2236 | 13611 | ||
| 2237 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13612 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 2237 | 13612 |
| 2237 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | Feature envy | t | f | t | 0 | 13612 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 2 | 2237 | 13612 | ||
| 2238 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13615 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 2 | 2238 | 13615 |
| 2239 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13618 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 1 | 2239 | 13618 |
| 2239 | YES I found bad smells the bad smells are: 1. Annotation overuse: the code contains multiple annotations which could indicate a lack of organization and readability. 2. Magic numbers: the value "0" in the getTabNames() method is a magic number and should be replaced with a descriptive constant. 3. Inconsistent formatting: the code has inconsistent spacing and indentation, making it hard to read and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | Annotation overuse: the code contains multiple annotations which could indicate a lack of organization and readability2 Magic numbers: the value "0" in the getTabNames() method is a magic number and should be replaced with a descriptive constant3 Inconsistent formatting: the code has inconsistent spacing and indentation, making it hard to read and maintain | t | f | f | . Annotation overuse: the code contains multiple annotations which could indicate a lack of organization and readability.2. Magic numbers: the value "0" in the getTabNames() method is a magic number and should be replaced with a descriptive constant.3. Inconsistent formatting: the code has inconsistent spacing and indentation, making it hard to read and maintain. | data class | 0 | 13618 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 2 | 2239 | 13618 |
| 2241 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | 1. long method | t | t | t | 0 | 13621 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 2241 | 13621 | ||
| 2241 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13621 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 2241 | 13621 | ||
| 2243 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13626 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 1 | 2243 | 13626 |
| 2243 | YES I found bad smellsThe bad smells are: 1. Feature envy: The method signatures for getHeaders(), getHost(), getSubProtocols(), getParameterMap(), getRequestURI(), and getQueryString() suggest that they may be better suited as methods on a different class. 2. Long parameter list: The methods setCookie(), setExtensions(), setHttpVersion(), setMethod(), setHeader(), setHeaders(), setSubProtocols() all have long parameter lists. These methods could be refactored to have fewer parameters or split into smaller, more specific methods. 3. Duplicate code: The method addExtensions() has two almost identical versions of the same code, one taking in an ExtensionConfig parameter and the other taking in a String parameter. These methods could be refactored to use a single method that handles both cases. 4. Inconsistent naming: The method getCookies() returns a List of Cookie objects, while the method getExtensions() returns a List of ExtensionConfig objects. This inconsistency in naming could lead to confusion for the users. 5. No comments or documentation: Although there are some comments scattered throughout the code, there is no overall description of the class or its methods. This lack of documentation could make it difficult for users to understand the purpose and usage of the class. 6. Deprecated method: The method clearHeaders() is marked as deprecated, but there is no explanation or alternative provided for users. This could potentially leave users confused and unsure of how to properly use the class. 7. Unused methods: The methods getHost(), getHttpVersion() and getMethod() are all unimplemented and do not serve any purpose. These methods should either be implemented or removed to avoid confusion for users. 8. Magic numbers: The method getHeaderInt() takes in a header name as a parameter, but the method name itself mentions "int". This could potentially lead to confusion for users as they may expect the method to return an int value instead of a String value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | Feature envy: The method signatures for getHeaders(), getHost(), getSubProtocols(), getParameterMap(), getRequestURI(), and getQueryString() suggest that they may be better suited as methods on a different class2 Long parameter list: The methods setCookie(), setExtensions(), setHttpVersion(), setMethod(), setHeader(), setHeaders(), setSubProtocols() all have long parameter lists These methods could be refactored to have fewer parameters or split into smaller, more specific methods3 Duplicate code: The method addExtensions() has two almost identical versions of the same code, one taking in an ExtensionConfig parameter and the other taking in a String parameter These methods could be refactored to use a single method that handles both cases4 Inconsistent naming: The method getCookies() returns a List of Cookie objects, while the method getExtensions() returns a List of ExtensionConfig objects This inconsistency in naming could lead to confusion for the users5 No comments or documentation: Although there are some comments scattered throughout the code, there is no overall description of the class or its methods This lack of documentation could make it difficult for users to understand the purpose and usage of the class6 Deprecated method: The method clearHeaders() is marked as deprecated, but there is no explanation or alternative provided for users This could potentially leave users confused and unsure of how to properly use the class7 Unused methods: The methods getHost(), getHttpVersion() and getMethod() are all unimplemented and do not serve any purpose These methods should either be implemented or removed to avoid confusion for users8 Magic numbers: The method getHeaderInt() takes in a header name as a parameter, but the method name itself mentions "int" This could potentially lead to confusion for users as they may expect the method to return an int value instead of a String value | t | f | f | . Feature envy: The method signatures for getHeaders(), getHost(), getSubProtocols(), getParameterMap(), getRequestURI(), and getQueryString() suggest that they may be better suited as methods on a different class.2. Long parameter list: The methods setCookie(), setExtensions(), setHttpVersion(), setMethod(), setHeader(), setHeaders(), setSubProtocols() all have long parameter lists. These methods could be refactored to have fewer parameters or split into smaller, more specific methods.3. Duplicate code: The method addExtensions() has two almost identical versions of the same code, one taking in an ExtensionConfig parameter and the other taking in a String parameter. These methods could be refactored to use a single method that handles both cases.4. Inconsistent naming: The method getCookies() returns a List of Cookie objects, while the method getExtensions() returns a List of ExtensionConfig objects. This inconsistency in naming could lead to confusion for the users.5. No comments or documentation: Although there are some comments scattered throughout the code, there is no overall description of the class or its methods. This lack of documentation could make it difficult for users to understand the purpose and usage of the class.6. Deprecated method: The method clearHeaders() is marked as deprecated, but there is no explanation or alternative provided for users. This could potentially leave users confused and unsure of how to properly use the class.7. Unused methods: The methods getHost(), getHttpVersion() and getMethod() are all unimplemented and do not serve any purpose. These methods should either be implemented or removed to avoid confusion for users.8. Magic numbers: The method getHeaderInt() takes in a header name as a parameter, but the method name itself mentions "int". This could potentially lead to confusion for users as they may expect the method to return an int value instead of a String value. | data class | 0 | 13626 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 2243 | 13626 |
| 2244 | { "output": "YES I found bad smells. the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | 1. data class | t | t | t | 0 | 13631 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 1 | 2244 | 13631 | ||
| 2244 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Misleading variable names 3. Unnecessary comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Duplicate code2 Misleading variable names3 Unnecessary comments | t | f | f | . Duplicate code2. Misleading variable names3. Unnecessary comments | data class | 0 | 13631 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 2 | 2244 | 13631 |
| 2245 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | data class | t | t | t | 0 | 13647 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 1 | 2245 | 13647 | ||
| 2245 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13647 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 2245 | 13647 |
| 2246 | {"response": "YES I found bad smells the bad smells are: Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13649 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 2246 | 13649 |
| 2246 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Large Class, 5. Shotgub surgery, 6. Data class, 7. Commented out code, 8. Manual getter/setter methods, 9. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | Long method, 2 Feature envy, 3 Magic numbers, 4 Large Class, 5 Shotgub surgery, 6 Data class, 7 Commented out code, 8 Manual getter/setter methods, 9 Code duplication | t | f | t | . Long method, 2. Feature envy, 3. Magic numbers, 4. Large Class, 5. Shotgub surgery, 7. Commented out code, 8. Manual getter/setter methods, 9. Code duplication. | 0 | 13649 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 2246 | 13649 | |
| 2247 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | data class, long method | t | t | t | long method | 0 | 13660 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 1 | 2247 | 13660 | |
| 2247 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 13660 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 2 | 2247 | 13660 |
| 2248 | { "input_code": "public class Calculator {\n public int sum(int a, int b) {\n int result = a + b;\n return result;\n }\n\n public int multiply(int a, int b) {\n int result = 0;\n for (int i = 0; i < b; i++) {\n result += a;\n }\n return result;\n }\n}", "detected_smells": { "Blob": false, "Data Class": false, "Feature Envy": false, "Long Method": true } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | false | 0 | 13661 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 1 | 2248 | 13661 | ||
| 2248 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13661 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 2 | 2248 | 13661 | ||
| 2249 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | long method | t | t | f | long method | data class | 0 | 13663 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 1 | 2249 | 13663 |
| 2249 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy: LimitedSizeDataCollection class is accessing and manipulating the data HashMap belonging to another class 3. Inconsistent naming conventions: The class name and method names are not consistent with the rest of the code's naming conventions 4. Magic numbers: The limitedSize value is hard-coded to a specific number instead of being declared as a constant or configurable variable 5. Incomplete exception handling: The UnsupportedOperationException is thrown for certain methods without any further handling or explanation 6. Multiple responsibilities: The LimitedSizeDataCollection class is responsible for both storing data in its own HashMap as well as providing methods for reading and writing data, causing it to have multiple responsibilities. 7. Misplaced methods: The writing and reading methods and variables do not seem to be relevant to the purpose of the LimitedSizeDataCollection class and should be located elsewhere. 8. Potential for data inconsistency: Since the writing and reading variables are volatile and can be accessed and modified by multiple methods, there is a potential for data inconsistency and synchronization issues. 9. Unnecessary comments: Some comments are providing redundant or obvious information and are not necessary. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | Long method2 Feature envy: LimitedSizeDataCollection class is accessing and manipulating the data HashMap belonging to another class3 Inconsistent naming conventions: The class name and method names are not consistent with the rest of the code's naming conventions4 Magic numbers: The limitedSize value is hard-coded to a specific number instead of being declared as a constant or configurable variable5 Incomplete exception handling: The UnsupportedOperationException is thrown for certain methods without any further handling or explanation6 Multiple responsibilities: The LimitedSizeDataCollection class is responsible for both storing data in its own HashMap as well as providing methods for reading and writing data, causing it to have multiple responsibilities7 Misplaced methods: The writing and reading methods and variables do not seem to be relevant to the purpose of the LimitedSizeDataCollection class and should be located elsewhere8 Potential for data inconsistency: Since the writing and reading variables are volatile and can be accessed and modified by multiple methods, there is a potential for data inconsistency and synchronization issues9 Unnecessary comments: Some comments are providing redundant or obvious information and are not necessary | t | f | f | . Long method2. Feature envy: LimitedSizeDataCollection class is accessing and manipulating the data HashMap belonging to another class3. Inconsistent naming conventions: The class name and method names are not consistent with the rest of the code's naming conventions4. Magic numbers: The limitedSize value is hard-coded to a specific number instead of being declared as a constant or configurable variable5. Incomplete exception handling: The UnsupportedOperationException is thrown for certain methods without any further handling or explanation6. Multiple responsibilities: The LimitedSizeDataCollection class is responsible for both storing data in its own HashMap as well as providing methods for reading and writing data, causing it to have multiple responsibilities.7. Misplaced methods: The writing and reading methods and variables do not seem to be relevant to the purpose of the LimitedSizeDataCollection class and should be located elsewhere.8. Potential for data inconsistency: Since the writing and reading variables are volatile and can be accessed and modified by multiple methods, there is a potential for data inconsistency and synchronization issues.9. Unnecessary comments: Some comments are providing redundant or obvious information and are not necessary. | data class | 0 | 13663 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 2 | 2249 | 13663 |
| 2250 | { "message": "YES I found bad smells", "bad smells are": [ "Feature envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13669 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 1 | 2250 | 13669 |
| 2250 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Hard-coded values 5. Lack of parameterization 6. Lack of abstraction and encapsulation 7. Use of raw types 8. Use of deprecated methods 9. Excessive use of conditional statements 10. Poor method and variable naming 11. Lack of comments and documentation 12. Poor error handling and exception handling 13. Unnecessary variables and loops. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | Long method2 Feature envy3 Duplicate code4 Hard-coded values5 Lack of parameterization6 Lack of abstraction and encapsulation7 Use of raw types8 Use of deprecated methods9 Excessive use of conditional statements | t | f | f | . Long method2. Feature envy3. Duplicate code4. Hard-coded values5. Lack of parameterization6. Lack of abstraction and encapsulation7. Use of raw types8. Use of deprecated methods9. Excessive use of conditional statements | data class | 0 | 13669 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 2 | 2250 | 13669 |
| 2251 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | long method, data class | t | t | t | long method | 0 | 13674 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 1 | 2251 | 13674 | |
| 2251 | YES I found bad smells the bad smells are: 1.Unused import, 2.Long method, 3.Magic number, 4.Inappropriate naming, 5.Unnecessary suppression, 6.Inconsistent indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | Unused import, 2Long method, 3Magic number, 4Inappropriate naming, 5Unnecessary suppression, 6Inconsistent indentation | t | f | f | .Unused import, 2.Long method, 3.Magic number, 4.Inappropriate naming, 5.Unnecessary suppression, 6.Inconsistent indentation | data class | 0 | 13674 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 2 | 2251 | 13674 |
| 2252 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | data class | t | t | t | 0 | 13680 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 2252 | 13680 | ||
| 2252 | YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | Long Method, 2 Feature Envy | t | f | f | . Long Method, 2. Feature Envy. | data class | 0 | 13680 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 2252 | 13680 |
| 2253 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | data class | t | t | t | 0 | 13685 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 1 | 2253 | 13685 | ||
| 2253 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13685 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 2253 | 13685 |
| 2254 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | 1. long method | t | t | t | 0 | 13687 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2254 | 13687 | ||
| 2254 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13687 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2254 | 13687 | ||
| 2255 | { "response": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | data class | t | t | t | 0 | 13690 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 1 | 2255 | 13690 | ||
| 2255 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13690 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 2 | 2255 | 13690 |
| 2256 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | data class | t | t | t | 0 | 13691 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 2256 | 13691 | ||
| 2256 | Yes I found bad smells. The bad smells are: 1. Feature envy, 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | Feature envy, 2 Long method | t | f | f | . Feature envy, 2. Long method. | data class | 0 | 13691 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 2256 | 13691 |
| 2257 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | long method | t | t | t | 0 | 13693 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 1 | 2257 | 13693 | ||
| 2257 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Deeply nested code, 6. Inconsistent formatting, 7. Coupling, 8. Lava flow code, 9. Cognitive complexity. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Deeply nested code, 6 Inconsistent formatting, 7 Coupling, 8 Lava flow code, 9 Cognitive complexity | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Deeply nested code, 6. Inconsistent formatting, 7. Coupling, 8. Lava flow code, 9. Cognitive complexity. | 0 | 13693 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 2 | 2257 | 13693 | |
| 2258 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | data class | t | t | t | 0 | 13695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 1 | 2258 | 13695 | ||
| 2258 | YES, I found bad smells The bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | Feature envy | t | f | f | .Feature envy | data class | 0 | 13695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 2 | 2258 | 13695 |
| 2259 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | long method | t | t | t | 0 | 13703 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 2259 | 13703 | ||
| 2259 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 13703 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 2259 | 13703 | |
| 2260 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13711 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 2260 | 13711 | |
| 2260 | YES, I found bad smells the bad smells are: 1. Commented out code 2. Multiple nested if-else statements 3. Use of instanceof operator 4. Use of a switch statement 5. Duplicate code 6. Naming conventions not followed (method name should be in lower camel case) 7. Inconsistent formatting/spacing 8. Long method (more than 10 lines of code) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Commented out code2 Multiple nested if-else statements3 Use of instanceof operator4 Use of a switch statement5 Duplicate code6 Naming conventions not followed (method name should be in lower camel case)7 Inconsistent formatting/spacing8 Long method (more than | t | f | t | 0 | 13711 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 2260 | 13711 | ||
| 2261 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13717 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 2 | 2261 | 13717 |
| 2262 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method | t | t | t | 0 | 13720 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 1 | 2262 | 13720 | ||
| 2262 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Nested loops 6. Conditional complexity 7. Misleading variable names 8. Hard-coded strings 9. Bad indentation and formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Nested loops6 Conditional complexity7 Misleading variable names8 Hard-coded strings9 Bad indentation and formatting | t | f | t | 0 | 13720 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 2 | 2262 | 13720 | ||
| 2265 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | data class | t | t | t | 0 | 13729 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 2265 | 13729 | ||
| 2265 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13729 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 2265 | 13729 |
| 2266 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | long method, data class | t | t | t | long method | 0 | 13732 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 2266 | 13732 | |
| 2266 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy (MetaColumn class has too much knowledge about other classes, such as DataType and Named) 3. Primitive obsession (using primitive data types instead of creating custom objects) 4. Data clumps (multiple attributes related to the same concept - tableCat, tableSchem, tableName) 5. Duplicated code (the constructor and the overridden method both use the same logic for assigning attribute values) 6. Use of null values (bufferLength = null, remarks = null, columnDef = null, sqlDataType = null, sqlDatetimeSub = null are all assigned null values) 7. Unnecessary use of final keyword (attributes are declared as final but never reassigned) 8. Inconsistent formatting (some attributes have spaces after the '=' while others do not) 9. Unnecessary use of @NotNull annotation (isAutoincrement and isGeneratedcolumn are assigned empty strings and do not need to be checked for null values) 10. Inefficient use of StringBuilder in the overridden method (using a StringBuilder to concatenate a single String value) 11. Unnecessary indentation (the constructor and the overridden method are indented differently) 12. Inconsistent naming conventions (some attributes use camelCase while others use snake_case) 13. Use of public attributes instead of private with getters and setters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | Long method 2 Feature envy (MetaColumn class has too much knowledge about other classes, such as DataType and Named)3 Primitive obsession (using primitive data types instead of creating custom objects)4 Data clumps (multiple attributes related to the same concept - tableCat, tableSchem, tableName)5 Duplicated code (the constructor and the overridden method both use the same logic for assigning attribute values)6 Use of null values (bufferLength = null, remarks = null, columnDef = null, sqlDataType = null, sqlDatetimeSub = null are all assigned null values)7 Unnecessary use of final keyword (attributes are declared as final but never reassigned)8 Inconsistent formatting (some attributes have spaces after the '=' while others do not)9 Unnecessary use of @NotNull annotation (isAutoincrement and isGeneratedcolumn are assigned empty strings and do not need to be checked for null values) | t | f | f | . Long method 2. Feature envy (MetaColumn class has too much knowledge about other classes, such as DataType and Named)3. Primitive obsession (using primitive data types instead of creating custom objects)4. Data clumps (multiple attributes related to the same concept - tableCat, tableSchem, tableName)5. Duplicated code (the constructor and the overridden method both use the same logic for assigning attribute values)6. Use of null values (bufferLength = null, remarks = null, columnDef = null, sqlDataType = null, sqlDatetimeSub = null are all assigned null values)7. Unnecessary use of final keyword (attributes are declared as final but never reassigned)8. Inconsistent formatting (some attributes have spaces after the '=' while others do not)9. Unnecessary use of @NotNull annotation (isAutoincrement and isGeneratedcolumn are assigned empty strings and do not need to be checked for null values) | data class | 0 | 13732 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 2266 | 13732 |
| 2267 | { "output": "YES, I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | data class, long method | t | t | t | long method | 0 | 13734 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 1 | 2267 | 13734 | |
| 2267 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 13734 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 2267 | 13734 |
| 2268 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13747 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 2268 | 13747 | |
| 2268 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Magic Numbers (such as the hardcoded value "80" in the method) 4. Inconsistent coding style (such as the mix of tabs and spaces) 5. Code duplication (such as the duplicate calls to LOG.isTraceEnabled()) 6. Insufficient argument validation (such as not checking if the list passed to handleBulkLoad() is null) 7. Use of deprecated methods (such as FileSystem.get(new URI(), Configuration)) 8. Poor exception handling (such as catching a generic IOException instead of specific exceptions) 9. Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) 10. Inefficient data structures (such as using nested Map and List structures instead of custom classes) 11. Insufficient comments and documentation (such as not providing javadocs for public methods and classes) 12. Use of raw types (such as Map, List without specifying the types) 13. Poor readability (such as the lack of indentation and the complex nested loops and conditional statements) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Long method2 Feature Envy3 Magic Numbers (such as the hardcoded value "80" in the method)4 Inconsistent coding style (such as the mix of tabs and spaces)5 Code duplication (such as the duplicate calls to LOGisTraceEnabled())6 Insufficient argument validation (such as not checking if the list passed to handleBulkLoad() is null)7 Use of deprecated methods (such as FileSystemget(new URI(), Configuration))8 Poor exception handling (such as catching a generic IOException instead of specific exceptions)9 Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) | t | f | t | Configuration))8. Poor exception handling (such as catching a generic IOException instead of specific exceptions)9. Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) | 0 | 13747 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 2268 | 13747 | |
| 2270 | {"response": "YES I found bad smells\nthe bad smells are: \n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 13763 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 1 | 2270 | 13763 |
| 2270 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13763 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 2 | 2270 | 13763 |
| 2271 | { "output": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | data class | t | t | t | 0 | 13766 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 1 | 2271 | 13766 | ||
| 2271 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13766 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 2 | 2271 | 13766 |
| 2272 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 13768 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2272 | 13768 | |
| 2272 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13768 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2272 | 13768 | ||
| 2274 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method, data class | t | t | t | data class | 0 | 13771 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 2274 | 13771 | |
| 2274 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 13771 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 2274 | 13771 | |
| 2275 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicUUID implements UUID, Formatable { /* ** Fields of BasicUUID */ private long majorId; // only using 48 bits private long timemillis; private int sequence; /* ** Methods of BasicUUID */ /** Constructor only called by BasicUUIDFactory. **/ public BasicUUID(long majorId, long timemillis, int sequence) { this.majorId = majorId; this.timemillis = timemillis; this.sequence = sequence; } /** Constructor only called by BasicUUIDFactory. Constructs a UUID from the string representation produced by toString. @see BasicUUID#toString **/ public BasicUUID(String uuidstring) { StringReader sr = new StringReader(uuidstring); sequence = (int) readMSB(sr); long ltimemillis = readMSB(sr) << 32; ltimemillis += readMSB(sr) << 16; ltimemillis += readMSB(sr); timemillis = ltimemillis; majorId = readMSB(sr); } /* * Formatable methods */ // no-arg constructor, required by Formatable public BasicUUID() { super(); } /** Write this out. @exception IOException error writing to log stream */ public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(majorId); out.writeLong(timemillis); out.writeInt(sequence); } /** Read this in @exception IOException error reading from log stream */ public void readExternal(ObjectInput in) throws IOException { majorId = in.readLong(); timemillis = in.readLong(); sequence = in.readInt(); } /** Return my format identifier. */ public int getTypeFormatId() { return StoredFormatIds.BASIC_UUID; } private static void writeMSB(char[] data, int offset, long value, int nbytes) { for (int i = nbytes - 1; i >= 0; i--) { long b = (value & (255L << (8 * i))) >>> (8 * i); int c = (int) ((b & 0xf0) >> 4); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); c = (int) (b & 0x0f); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); } } /** Read a long value, msb first, from its character representation in the string reader, using '-' or end of string to delimit. **/ private static long readMSB(StringReader sr) { long value = 0; try { int c; while ((c = sr.read()) != -1) { if (c == '-') break; value <<= 4; int nibble; if (c <= '9') nibble = c - '0'; else if (c <= 'F') nibble = c - 'A' + 10; else nibble = c - 'a' + 10; value += nibble; } } catch (Exception e) { } return value; } /* ** Methods of UUID */ /** Implement value equality. **/ public boolean equals(Object otherObject) { if (!(otherObject instanceof BasicUUID)) return false; BasicUUID other = (BasicUUID) otherObject; return (this.sequence == other.sequence) && (this.timemillis == other.timemillis) && (this.majorId == other.majorId); } /** Provide a hashCode which is compatible with the equals() method. **/ public int hashCode() { long hc = majorId ^ timemillis; return sequence ^ ((int) (hc >> 4)); } /** Produce a string representation of this UUID which can be passed to UUIDFactory.recreateUUID later on to reconstruct it. The funny representation is designed to (sort of) match the format of Microsoft's UUIDGEN utility. */ public String toString() {return stringWorkhorse( '-' );} /** Produce a string representation of this UUID which is suitable for use as a unique ANSI identifier. */ public String toANSIidentifier() {return "U" + stringWorkhorse( 'X' );} /** * Private workhorse of the string making routines. * * @param separator Character to separate number blocks. * Null means do not include a separator. * * @return string representation of UUID. */ public String stringWorkhorse( char separator ) { char[] data = new char[36]; writeMSB(data, 0, (long) sequence, 4); int offset = 8; if (separator != 0) data[offset++] = separator; long ltimemillis = timemillis; writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, majorId, 6); offset += 12; return new String(data, 0, offset); } /** Clone this UUID. @return a copy of this UUID */ public UUID cloneMe() { return new BasicUUID(majorId, timemillis, sequence); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13773 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/services/uuid/BasicUUID.java/#L36-L250 | 1 | 2275 | 13773 |
| 2275 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicUUID implements UUID, Formatable { /* ** Fields of BasicUUID */ private long majorId; // only using 48 bits private long timemillis; private int sequence; /* ** Methods of BasicUUID */ /** Constructor only called by BasicUUIDFactory. **/ public BasicUUID(long majorId, long timemillis, int sequence) { this.majorId = majorId; this.timemillis = timemillis; this.sequence = sequence; } /** Constructor only called by BasicUUIDFactory. Constructs a UUID from the string representation produced by toString. @see BasicUUID#toString **/ public BasicUUID(String uuidstring) { StringReader sr = new StringReader(uuidstring); sequence = (int) readMSB(sr); long ltimemillis = readMSB(sr) << 32; ltimemillis += readMSB(sr) << 16; ltimemillis += readMSB(sr); timemillis = ltimemillis; majorId = readMSB(sr); } /* * Formatable methods */ // no-arg constructor, required by Formatable public BasicUUID() { super(); } /** Write this out. @exception IOException error writing to log stream */ public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(majorId); out.writeLong(timemillis); out.writeInt(sequence); } /** Read this in @exception IOException error reading from log stream */ public void readExternal(ObjectInput in) throws IOException { majorId = in.readLong(); timemillis = in.readLong(); sequence = in.readInt(); } /** Return my format identifier. */ public int getTypeFormatId() { return StoredFormatIds.BASIC_UUID; } private static void writeMSB(char[] data, int offset, long value, int nbytes) { for (int i = nbytes - 1; i >= 0; i--) { long b = (value & (255L << (8 * i))) >>> (8 * i); int c = (int) ((b & 0xf0) >> 4); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); c = (int) (b & 0x0f); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); } } /** Read a long value, msb first, from its character representation in the string reader, using '-' or end of string to delimit. **/ private static long readMSB(StringReader sr) { long value = 0; try { int c; while ((c = sr.read()) != -1) { if (c == '-') break; value <<= 4; int nibble; if (c <= '9') nibble = c - '0'; else if (c <= 'F') nibble = c - 'A' + 10; else nibble = c - 'a' + 10; value += nibble; } } catch (Exception e) { } return value; } /* ** Methods of UUID */ /** Implement value equality. **/ public boolean equals(Object otherObject) { if (!(otherObject instanceof BasicUUID)) return false; BasicUUID other = (BasicUUID) otherObject; return (this.sequence == other.sequence) && (this.timemillis == other.timemillis) && (this.majorId == other.majorId); } /** Provide a hashCode which is compatible with the equals() method. **/ public int hashCode() { long hc = majorId ^ timemillis; return sequence ^ ((int) (hc >> 4)); } /** Produce a string representation of this UUID which can be passed to UUIDFactory.recreateUUID later on to reconstruct it. The funny representation is designed to (sort of) match the format of Microsoft's UUIDGEN utility. */ public String toString() {return stringWorkhorse( '-' );} /** Produce a string representation of this UUID which is suitable for use as a unique ANSI identifier. */ public String toANSIidentifier() {return "U" + stringWorkhorse( 'X' );} /** * Private workhorse of the string making routines. * * @param separator Character to separate number blocks. * Null means do not include a separator. * * @return string representation of UUID. */ public String stringWorkhorse( char separator ) { char[] data = new char[36]; writeMSB(data, 0, (long) sequence, 4); int offset = 8; if (separator != 0) data[offset++] = separator; long ltimemillis = timemillis; writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, majorId, 6); offset += 12; return new String(data, 0, offset); } /** Clone this UUID. @return a copy of this UUID */ public UUID cloneMe() { return new BasicUUID(majorId, timemillis, sequence); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13773 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/services/uuid/BasicUUID.java/#L36-L250 | 2 | 2275 | 13773 |
| 2276 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13775 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 2276 | 13775 |
| 2278 | { "output": "YES I found bad smells. The bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | 2. data class | t | t | t | 0 | 13783 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 1 | 2278 | 13783 | ||
| 2278 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13783 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 2 | 2278 | 13783 |
| 2279 | YES, I found bad smells The bad smells are: 1. Feature envy - the ConfigBoolean class depends mostly on the OptionSpec class, suggesting a possible design flaw. 2. Long method - the ConfigBoolean class has multiple methods that perform multiple tasks, potentially making it difficult to maintain and extend. 3. Duplicate code - the set() method is duplicated with different parameters, suggesting redundancy in the code. 4. Primitive obsession - the ConfigBoolean class is using primitive boolean values instead of a boolean object, potentially making it difficult to maintain and extend. 5. Lack of cohesion - the addToCommandline() method does not seem to fit with the purpose of the ConfigBoolean class, suggesting a possible lack of cohesion in the code. 6. Poor exception handling - the parseValue() method does not handle potential exceptions or errors that may occur when parsing the input value, making the code less robust. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | Feature envy - the ConfigBoolean class depends mostly on the OptionSpec class, suggesting a possible design flaw2 Long method - the ConfigBoolean class has multiple methods that perform multiple tasks, potentially making it difficult to maintain and extend3 Duplicate code - the set() method is duplicated with different parameters, suggesting redundancy in the code4 Primitive obsession - the ConfigBoolean class is using primitive boolean values instead of a boolean object, potentially making it difficult to maintain and extend5 Lack of cohesion - the addToCommandline() method does not seem to fit with the purpose of the ConfigBoolean class, suggesting a possible lack of cohesion in the code6 Poor exception handling - the parseValue() method does not handle potential exceptions or errors that may occur when parsing the input value, making the code less robust | t | f | f | . Feature envy - the ConfigBoolean class depends mostly on the OptionSpec class, suggesting a possible design flaw.2. Long method - the ConfigBoolean class has multiple methods that perform multiple tasks, potentially making it difficult to maintain and extend.3. Duplicate code - the set() method is duplicated with different parameters, suggesting redundancy in the code.4. Primitive obsession - the ConfigBoolean class is using primitive boolean values instead of a boolean object, potentially making it difficult to maintain and extend.5. Lack of cohesion - the addToCommandline() method does not seem to fit with the purpose of the ConfigBoolean class, suggesting a possible lack of cohesion in the code.6. Poor exception handling - the parseValue() method does not handle potential exceptions or errors that may occur when parsing the input value, making the code less robust. | data class | 0 | 13785 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 2 | 2279 | 13785 |
| 2280 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | data class | t | t | t | 0 | 13797 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 1 | 2280 | 13797 | ||
| 2280 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Poor variable naming 5. Mix of string concatenation and string formatting methods 6. Code formatting issues 7. Lack of comments or documentation 8. Lack of access modifiers for class fields 9. Lack of proper exception handling 10. Unnecessary override of methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | Long method2 Feature envy3 Code duplication4 Poor variable naming5 Mix of string concatenation and string formatting methods 6 Code formatting issues 7 Lack of comments or documentation8 Lack of access modifiers for class fields9 Lack of proper exception handling | t | f | f | . Long method2. Feature envy3. Code duplication4. Poor variable naming5. Mix of string concatenation and string formatting methods 6. Code formatting issues 7. Lack of comments or documentation8. Lack of access modifiers for class fields9. Lack of proper exception handling | data class | 0 | 13797 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 2 | 2280 | 13797 |
| 2281 | { "output": "YES I found bad smells", "the bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | data class | t | t | t | 0 | 13809 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 2281 | 13809 | ||
| 2281 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13809 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 2281 | 13809 |
| 2282 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 13839 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 1 | 2282 | 13839 |
| 2282 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13839 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 2 | 2282 | 13839 |
| 2283 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | long method, data class | t | t | t | long method | 0 | 13842 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 2283 | 13842 | |
| 2283 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Primitive Obsession 4. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Long Method2 Feature Envy3 Primitive Obsession4 Inappropriate Intimacy | t | f | f | . Long Method2. Feature Envy3. Primitive Obsession4. Inappropriate Intimacy | data class | 0 | 13842 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 2283 | 13842 |
| 2284 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | data class | t | t | t | 0 | 13857 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 2284 | 13857 | ||
| 2284 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13857 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 2284 | 13857 |
| 2285 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | long method | t | t | f | long method | data class | 0 | 13867 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 1 | 2285 | 13867 |
| 2285 | YES I found bad smells the bad smells are: 1.Long Method, 2.Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | Long Method, 2Feature Envy | t | f | f | .Long Method, 2.Feature Envy | data class | 0 | 13867 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 2285 | 13867 |
| 2286 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | data class | t | t | t | 0 | 13880 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 2286 | 13880 | ||
| 2286 | YES I found bad smells The bad smells are: 1. Long parameter list, 2. Long method, 3. Feature envy (getFullContentOctets), 4. Inappropriate intimacy (The class has access to the internals of SharedInputStream rather than using encapsulation), 5. Inconsistent naming conventions (size and textualLineCount variables start with lowercase but subType and mediaType start with uppercase), 6. Data class (only contains data and no behavior), 7. Inconsistent importing (some classes are imported with the full package name, others are not), 8. Lack of documentation or comments, 9. Duplication of code (the second constructor calls the first one), 10. Primitive obsession (use of primitive data types rather than creating custom objects), 11. Unnecessary constructor (the second constructor is not needed since it just calls the first one with an additional parameter), 12. Lack of cohesion (the class handles both message properties and attachments), 13. Unnecessary public access modifiers (the methods could be made private since they are only used within the class), 14. Lack of abstraction (the class directly accesses the SharedInputStream rather than using a more abstract layer). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long parameter list, 2 Long method, 3 Feature envy (getFullContentOctets), 4 Inappropriate intimacy (The class has access to the internals of SharedInputStream rather than using encapsulation), 5 Inconsistent naming conventions (size and textualLineCount variables start with lowercase but subType and mediaType start with uppercase), 6 Data class (only contains data and no behavior), 7 Inconsistent importing (some classes are imported with the full package name, others are not), 8 Lack of documentation or comments, 9 Duplication of code (the second constructor calls the first one), | t | f | t | . Long parameter list, 2. Long method, 3. Feature envy (getFullContentOctets), 4. Inappropriate intimacy (The class has access to the internals of SharedInputStream rather than using encapsulation), 5. Inconsistent naming conventions (size and textualLineCount variables start with lowercase but subType and mediaType start with uppercase), 7. Inconsistent importing (some classes are imported with the full package name, others are not), 8. Lack of documentation or comments, 9. Duplication of code (the second constructor calls the first one), | 0 | 13880 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 2286 | 13880 | |
| 2287 | YES I found bad smells The bad smells are: 1. Long class 2. Data class 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | Long class2 Data class3 Primitive obsession | t | f | t | 0 | 13890 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 2287 | 13890 | ||
| 2288 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | f | f | f | data class | 0 | 13898 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 2288 | 13898 | ||
| 2288 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | data class | t | t | t | 0 | 13898 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 2288 | 13898 | ||
| 2289 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | data class, long method | t | t | t | long method | 0 | 13914 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 1 | 2289 | 13914 | |
| 2289 | YES I found bad smells! The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13914 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 2 | 2289 | 13914 |
| 2291 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | data class | t | t | t | 0 | 13942 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 1 | 2291 | 13942 | ||
| 2291 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | Long method2Feature envy | t | f | f | .Long method2.Feature envy | data class | 0 | 13942 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 2 | 2291 | 13942 |
| 2294 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13978 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 2 | 2294 | 13978 |
| 2295 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13990 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 1 | 2295 | 13990 |
| 2295 | YES, I found bad smells. The bad smells are: 1. Feature envy 2. Inconsistent formatting 3. Code duplication 4. Magic numbers/unclear purpose of code 5. Use of assert statement as hack | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | Feature envy2 Inconsistent formatting3 Code duplication4 Magic numbers/unclear purpose of code5 Use of assert statement as hack | t | f | f | . Feature envy2. Inconsistent formatting3. Code duplication4. Magic numbers/unclear purpose of code5. Use of assert statement as hack | data class | 0 | 13990 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 2 | 2295 | 13990 |
| 2296 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | f | f | f | data class | 0 | 14009 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 2296 | 14009 | ||
| 2296 | {"response": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | 1. data class | t | t | t | 0 | 14009 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 2296 | 14009 | ||
| 2297 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 14024 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 2297 | 14024 | ||
| 2297 | YES, I found bad smells: 1. Long method 2. Complex code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Complex code | t | f | t | 0 | 14024 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 2297 | 14024 | ||
| 2298 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | long method, data class | t | t | t | data class | 0 | 14025 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 2298 | 14025 | |
| 2298 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14025 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 2298 | 14025 | ||
| 2299 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | \n1. long method | t | t | t | 0 | 14028 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 2299 | 14028 | ||
| 2299 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Duplicate code 4. Hardcoded values 5. Unused variables 6. Poor exception handling 7. Excessive commenting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method2 Magic numbers3 Duplicate code4 Hardcoded values5 Unused variables6 Poor exception handling7 Excessive commenting | t | f | t | 0 | 14028 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 2299 | 14028 | ||
| 2300 | {"message": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | data class | t | t | t | 0 | 14030 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 1 | 2300 | 14030 | ||
| 2300 | YES I found bad smells the bad smells are: Feature envy, Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | Feature envy, Long method | t | f | f | Feature envy, Long method | data class | 0 | 14030 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 2 | 2300 | 14030 |
| 2301 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14036 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 2 | 2301 | 14036 |
| 2302 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, data class | t | t | t | data class | 0 | 14043 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 2302 | 14043 | |
| 2302 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Feature envy | t | f | f | . Feature envy | long method | 0 | 14043 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 2302 | 14043 |
| 2303 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | f | f | f | data class | 0 | 14060 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 2 | 2303 | 14060 | ||
| 2303 | { "response": "YES, I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | data class | t | t | t | 0 | 14060 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 1 | 2303 | 14060 | ||
| 2304 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | long method | t | t | t | 0 | 14061 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 2304 | 14061 | ||
| 2304 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent formatting/layout 5. Magic numbers/constants 6. Non-descriptive variable names 7. Use of multiple nested if-else statements 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method2 Feature envy3 Duplicated code4 Inconsistent formatting/layout5 Magic numbers/constants6 Non-descriptive variable names7 Use of multiple nested if-else statements8 Lack of comments/documentation | t | f | t | 0 | 14061 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 2304 | 14061 | ||
| 2306 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | 1. long method | t | t | t | 0 | 14069 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 1 | 2306 | 14069 | ||
| 2306 | YES I found bad smells" 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14069 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 2 | 2306 | 14069 | ||
| 2307 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14085 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 2307 | 14085 | |
| 2307 | YES I found bad smells the bad smells are: 1. long method 2. feature envy 3. inconsistent naming conventions 4. unnecessary comments 5. lack of proper documentation or comments 6. hard-coded values 7. unnecessary type casting 8. long variable names 9. nested loops 10. excessive use of if/else statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method2 feature envy3 inconsistent naming conventions4 unnecessary comments5 lack of proper documentation or comments6 hard-coded values7 unnecessary type casting8 long variable names9 nested loops | t | f | t | 0 | 14085 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 2307 | 14085 | ||
| 2308 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | data class, long method | t | t | t | long method | 0 | 14094 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 1 | 2308 | 14094 | |
| 2308 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14094 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 2308 | 14094 |
| 2309 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method | t | t | t | 0 | 14095 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2309 | 14095 | ||
| 2309 | YES, I found bad smells the bad smells are: 1.Long method, 2.Duplicated code, 3.Magic number, 4.Inappropriate comments, 5.Lazy class, 6.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method, 2Duplicated code, 3Magic number, 4Inappropriate comments, 5Lazy class, 6Feature envy | t | f | t | 2.Duplicated code, 3.Magic number, 4.Inappropriate comments, 5.Lazy class, 6.Feature envy | 0 | 14095 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2309 | 14095 | |
| 2310 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14096 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2310 | 14096 |
| 2310 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14096 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2310 | 14096 | ||
| 2312 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | data class | t | t | t | 0 | 14102 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 1 | 2312 | 14102 | ||
| 2312 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14102 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 2 | 2312 | 14102 |
| 2316 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 14118 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 2316 | 14118 |
| 2316 | YES I found bad smells the bad smells are: 1. Long method 2. Parallel inheritance hierarchies | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | Long method 2 Parallel inheritance hierarchies | t | f | f | . Long method 2. Parallel inheritance hierarchies | feature envy | 0 | 14118 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 2316 | 14118 |
| 2317 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 14122 | https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 | 1 | 2317 | 14122 | |
| 2317 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Temporary field 4. Shotgun surgery 5. Primitive obsession 6. Message chain 7. Inappropriate intimacy 8. Data clumps 9. Data class 10. Inconsistent naming convention 11. Deeply nested code 12. Feature envy between Map and PartitionCollapsingSchemas classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } } |
data class | Long method2 Feature envy3 Temporary field4 Shotgun surgery5 Primitive obsession6 Message chain7 Inappropriate intimacy8 Data clumps9 Data class | t | f | t | 0 | 14122 | https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 | 2 | 2317 | 14122 | ||
| 2318 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | data class | t | t | t | 0 | 14124 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 2318 | 14124 | ||
| 2318 | YES I found bad smells! The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14124 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 2318 | 14124 |
| 2321 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14130 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 2321 | 14130 |
| 2321 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | Long methods2 Feature envy | t | f | f | . Long methods2. Feature envy | data class | 0 | 14130 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 2321 | 14130 |
| 2323 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14132 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 2 | 2323 | 14132 |
| 2324 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | data class, long method | t | t | t | long method | 0 | 14136 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 1 | 2324 | 14136 | |
| 2324 | YES I found bad smells the bad smells are: 1. Long method 2. LimitedSizeDataCollection class is not domain specific, it has no clear purpose or responsibility 3. Writing and reading boolean variables are not used effectively and could cause issues with access to the data 4. Excessive use of volatile keyword could indicate a lack of understanding of threads and synchronization 5. Inconsistent naming conventions 6. Unsupported operations should not be publicly accessible 7. Poorly structured and confusing logic in the put method 8. The put method is doing more than one thing and should be split into smaller methods 9. Collection interface is unnecessarily implemented 10. Inefficient use of data structures, LinkedList and ArrayList are being used when other data structures might be more appropriate 11. Nested loops and conditional statements can be hard to follow and difficult to debug 12. Lack of comments and documentation, making it hard for others to understand the code 13. Code duplication, specifically in the finishWriting and finishReading methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | Long method 2 LimitedSizeDataCollection class is not domain specific, it has no clear purpose or responsibility 3 Writing and reading boolean variables are not used effectively and could cause issues with access to the data 4 Excessive use of volatile keyword could indicate a lack of understanding of threads and synchronization 5 Inconsistent naming conventions 6 Unsupported operations should not be publicly accessible 7 Poorly structured and confusing logic in the put method 8 The put method is doing more than one thing and should be split into smaller methods 9 Collection interface is unnecessarily implemented | t | f | f | . Long method 2. LimitedSizeDataCollection class is not domain specific, it has no clear purpose or responsibility 3. Writing and reading boolean variables are not used effectively and could cause issues with access to the data 4. Excessive use of volatile keyword could indicate a lack of understanding of threads and synchronization 5. Inconsistent naming conventions 6. Unsupported operations should not be publicly accessible 7. Poorly structured and confusing logic in the put method 8. The put method is doing more than one thing and should be split into smaller methods 9. Collection interface is unnecessarily implemented | data class | 0 | 14136 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 2 | 2324 | 14136 |
| 2325 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14140 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 2325 | 14140 |
| 2326 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | 1. long method | t | t | t | 0 | 14143 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 2326 | 14143 | ||
| 2326 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Feature envy, 2Long method | t | f | t | .Feature envy | 0 | 14143 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 2326 | 14143 | |
| 2327 | {"response":"YES I found bad smells","bad smells":"1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14144 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 2327 | 14144 |
| 2327 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14144 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 2327 | 14144 | |
| 2328 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14146 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 1 | 2328 | 14146 |
| 2328 | YES I found bad smells the bad smells are: 1. Long method 2. Primitive obsession 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
feature envy | Long method 2 Primitive obsession 3 Feature envy | t | f | t | 0 | 14146 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 2 | 2328 | 14146 | ||
| 2330 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | data class, long method | t | t | t | long method | 0 | 14150 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 2330 | 14150 | |
| 2330 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14150 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 2330 | 14150 |
| 2333 | YES, I found bad smells the bad smells are: 1. Long method 2. Large class 3. Feature envy: HistoryClientService is accessing and manipulating data from other classes (HistoryContext, JHSDelegationTokenSecretManager, etc.) instead of being self-contained. 4. Duplication: getConfig() and getConfig().getInt() are repeated multiple times in the code. 5. Magic numbers: Default values and ports are hard coded instead of being declared as constants. 6. Inconsistent naming conventions: the use of both snake_case and camelCase in variable names. 7. Use of nested classes: The class HSClientProtocolHandler is declared within the HistoryClientService class instead of being a separate top-level class. 8. Single responsibility principle violation: The HistoryClientService class is responsible for both handling requests from clients and managing the server and webApp. 9. Incomplete error handling: Some methods, such as killJob(), do not handle errors properly and just throw IOExceptions. 10. Method chaining: The method WebApps.$for() is used for creating the webApp variable in a single line, making it difficult to understand what is happening. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | Long method2 Large class3 Feature envy: HistoryClientService is accessing and manipulating data from other classes (HistoryContext, JHSDelegationTokenSecretManager, etc) instead of being self-contained4 Duplication: getConfig() and getConfig()getInt() are repeated multiple times in the code5 Magic numbers: Default values and ports are hard coded instead of being declared as constants6 Inconsistent naming conventions: the use of both snake_case and camelCase in variable names 7 Use of nested classes: The class HSClientProtocolHandler is declared within the HistoryClientService class instead of being a separate top-level class8 Single responsibility principle violation: The HistoryClientService class is responsible for both handling requests from clients and managing the server and webApp9 Incomplete error handling: Some methods, such as killJob(), do not handle errors properly and just throw IOExceptions | t | f | f | . Long method2. Large class3. Feature envy: HistoryClientService is accessing and manipulating data from other classes (HistoryContext, JHSDelegationTokenSecretManager, etc.) instead of being self-contained.4. Duplication: getConfig() and getConfig().getInt() are repeated multiple times in the code.5. Magic numbers: Default values and ports are hard coded instead of being declared as constants.6. Inconsistent naming conventions: the use of both snake_case and camelCase in variable names. 7. Use of nested classes: The class HSClientProtocolHandler is declared within the HistoryClientService class instead of being a separate top-level class.8. Single responsibility principle violation: The HistoryClientService class is responsible for both handling requests from clients and managing the server and webApp.9. Incomplete error handling: Some methods, such as killJob(), do not handle errors properly and just throw IOExceptions. | data class | 0 | 14159 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 2333 | 14159 |
| 2335 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | data class | t | t | t | 0 | 14161 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 2335 | 14161 | ||
| 2335 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14161 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 2335 | 14161 |
| 2336 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | data class, long method | t | t | t | long method | 0 | 14164 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 1 | 2336 | 14164 | |
| 2336 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate Code 4. Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | Long method2 Feature envy3 Duplicate Code4 Conditional complexity | t | f | f | . Long method2. Feature envy3. Duplicate Code4. Conditional complexity | data class | 0 | 14164 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 2 | 2336 | 14164 |
| 2337 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1. Data Class": "DCSerialField class seems to be a Data Class as it holds only data and has minimal behavior" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | 1. data class: dcserialfield class seems to be a data class as it holds only data and has minimal behavior | t | t | t | 0 | 14166 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 1 | 2337 | 14166 | ||
| 2337 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14166 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 2 | 2337 | 14166 |
| 2340 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | long method | t | t | t | 0 | 14174 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 1 | 2340 | 14174 | ||
| 2340 | YES, bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14174 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 2 | 2340 | 14174 | ||
| 2341 | YES I found bad smells The bad smells are: 1. Mutable state 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | Mutable state2 Long method 3 Feature envy | t | f | f | . Mutable state2. Long method 3. Feature envy | data class | 0 | 14178 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 2 | 2341 | 14178 |
| 2342 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | long method | t | t | t | 0 | 14179 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 2342 | 14179 | ||
| 2342 | YES I found bad smells. The bad smells are:Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 14179 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 2342 | 14179 | |
| 2343 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | data class, long method | t | t | t | data class | 0 | 14182 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 1 | 2343 | 14182 | |
| 2343 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14182 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 2 | 2343 | 14182 | ||
| 2344 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | long method, data class | t | t | t | long method | 0 | 14186 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 1 | 2344 | 14186 | |
| 2344 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14186 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 2 | 2344 | 14186 |
| 2345 | {"response": "YES, I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | 1. long method | t | t | t | 0 | 14192 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 2345 | 14192 | ||
| 2345 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14192 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 2345 | 14192 | ||
| 2346 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | 1. data class | t | t | t | 0 | 14193 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 1 | 2346 | 14193 | ||
| 2346 | YES I found bad smells The bad smells are: 1. Data class 2. Lack of encapsulation 3. Long method 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | Data class2 Lack of encapsulation3 Long method4 Feature envy | t | f | t | 0 | 14193 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 2 | 2346 | 14193 | ||
| 2347 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | long method, data class | t | t | t | long method | 0 | 14196 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 2347 | 14196 | |
| 2347 | YES I found bad smells the bad smells are: 1. Feature Envy - The class is heavily dependent on external classes such as Primitives, ParameterizedType, and Class. 2. Long Method - The constructor and the analyzeParametrizedType methods are quite lengthy and could potentially be simplified. 3. Inconsistent Naming - Some variable names are in camelCase while others are in snake_case, making the code less readable. 4. Low Cohesion - The class has multiple responsibilities, such as converting types and analyzing them, which could be split into separate classes. 5. Inappropriate Intimacy - The class is tightly coupled with external classes, making it difficult to modify or extend. 6. Shotgun Surgery - Any changes to external classes or the structure of the constructor could require changes to this class as well, leading to code duplication. 7. Incomplete Abstraction - The class directly accesses and uses the fields and methods of external classes, instead of abstracting them away. 8. Primitive Obsession - The class has multiple boolean fields to represent different types, which could be abstracted into one single Enum field. 9. Data Clumps - The class uses multiple related fields to represent the type and subtype relationship, which could be better represented as a single field or class. 10. Lack of Encapsulation - The class exposes all of its fields publicly, which could lead to unwanted modifications or misuse. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Feature Envy - The class is heavily dependent on external classes such as Primitives, ParameterizedType, and Class2 Long Method - The constructor and the analyzeParametrizedType methods are quite lengthy and could potentially be simplified3 Inconsistent Naming - Some variable names are in camelCase while others are in snake_case, making the code less readable4 Low Cohesion - The class has multiple responsibilities, such as converting types and analyzing them, which could be split into separate classes5 Inappropriate Intimacy - The class is tightly coupled with external classes, making it difficult to modify or extend6 Shotgun Surgery - Any changes to external classes or the structure of the constructor could require changes to this class as well, leading to code duplication7 Incomplete Abstraction - The class directly accesses and uses the fields and methods of external classes, instead of abstracting them away8 Primitive Obsession - The class has multiple boolean fields to represent different types, which could be abstracted into one single Enum field9 Data Clumps - The class uses multiple related fields to represent the type and subtype relationship, which could be better represented as a single field or class | t | f | f | . Feature Envy - The class is heavily dependent on external classes such as Primitives, ParameterizedType, and Class.2. Long Method - The constructor and the analyzeParametrizedType methods are quite lengthy and could potentially be simplified.3. Inconsistent Naming - Some variable names are in camelCase while others are in snake_case, making the code less readable.4. Low Cohesion - The class has multiple responsibilities, such as converting types and analyzing them, which could be split into separate classes.5. Inappropriate Intimacy - The class is tightly coupled with external classes, making it difficult to modify or extend.6. Shotgun Surgery - Any changes to external classes or the structure of the constructor could require changes to this class as well, leading to code duplication.7. Incomplete Abstraction - The class directly accesses and uses the fields and methods of external classes, instead of abstracting them away.8. Primitive Obsession - The class has multiple boolean fields to represent different types, which could be abstracted into one single Enum field.9. Data Clumps - The class uses multiple related fields to represent the type and subtype relationship, which could be better represented as a single field or class. | data class | 0 | 14196 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 2347 | 14196 |
| 2348 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | data class | t | t | t | 0 | 14198 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 1 | 2348 | 14198 | ||
| 2348 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14198 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 2 | 2348 | 14198 |
| 2351 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | data class | t | t | t | 0 | 14219 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 2351 | 14219 | ||
| 2351 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14219 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 2351 | 14219 |
| 2352 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 14223 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2352 | 14223 | ||
| 2352 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | long method | t | t | f | long method | data class | 0 | 14223 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2352 | 14223 |
| 2354 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | long method | t | t | f | long method | data class | 0 | 14226 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 1 | 2354 | 14226 |
| 2354 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14226 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 2 | 2354 | 14226 |
| 2356 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14230 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 1 | 2356 | 14230 | ||
| 2356 | YES, I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy | t | f | f | .Feature envy | data class | 0 | 14230 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 2 | 2356 | 14230 |
| 2357 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14232 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 1 | 2357 | 14232 |
| 2357 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy: methods in subclasses of PendingActionNotificationResponse are accessing data from the superclass instead of using their own data, 3. Speculative generality: abstract class is unnecessary, 4. Inconsistent formatting, 5. Inappropriate naming, 6. Feature envy: inner class accessing data from outer class, 7. Inappropriate use of annotations, 8. Coupled structure: subclasses have nearly identical structure, 9. Inappropriate use of inheritance, 10. Inappropriate comments: comments are not useful and add clutter to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | Long method, 2 Feature envy: methods in subclasses of PendingActionNotificationResponse are accessing data from the superclass instead of using their own data, 3 Speculative generality: abstract class is unnecessary, 4 Inconsistent formatting, 5 Inappropriate naming, 6 Feature envy: inner class accessing data from outer class, 7 Inappropriate use of annotations, 8 Coupled structure: subclasses have nearly identical structure, 9 Inappropriate use of inheritance, | t | f | f | . Long method, 2. Feature envy: methods in subclasses of PendingActionNotificationResponse are accessing data from the superclass instead of using their own data, 3. Speculative generality: abstract class is unnecessary, 4. Inconsistent formatting, 5. Inappropriate naming, 6. Feature envy: inner class accessing data from outer class, 7. Inappropriate use of annotations, 8. Coupled structure: subclasses have nearly identical structure, 9. Inappropriate use of inheritance, | data class | 0 | 14232 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 2357 | 14232 |
| 2358 | { "output": "YES I found bad smells, the bad smells are: 1. Long method", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14233 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 2358 | 14233 |
| 2358 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14233 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 2358 | 14233 | ||
| 2359 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14234 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 2359 | 14234 | |
| 2359 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | Long method | t | f | t | 0 | 14234 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 2359 | 14234 | ||
| 2360 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | data class, long method | t | t | t | long method | 0 | 14236 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 1 | 2360 | 14236 | |
| 2360 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14236 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 2 | 2360 | 14236 |
| 2361 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | long method | t | t | t | 0 | 14251 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 2361 | 14251 | ||
| 2361 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | Long method | t | f | t | 0 | 14251 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 2361 | 14251 | ||
| 2362 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14252 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 2362 | 14252 |
| 2362 | YES I found bad smells The bad smells are: 1. Raw type usage 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
feature envy | Raw type usage2 Long method3 Feature envy | t | f | t | 0 | 14252 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 2362 | 14252 | ||
| 2363 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | long method, data class | t | t | t | long method | 0 | 14254 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 1 | 2363 | 14254 | |
| 2363 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14254 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 2 | 2363 | 14254 |
| 2364 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | 1. data class | t | t | t | 0 | 14255 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 1 | 2364 | 14255 | ||
| 2364 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14255 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 2 | 2364 | 14255 |
| 2366 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14296 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 2 | 2366 | 14296 |
| 2367 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | f | f | f | data class | 0 | 14300 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 2 | 2367 | 14300 | ||
| 2367 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | data class, long method | t | t | t | long method | 0 | 14300 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 1 | 2367 | 14300 | |
| 2368 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | long method, data class | t | t | t | data class | 0 | 14301 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 2368 | 14301 | |
| 2368 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14301 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 2368 | 14301 | ||
| 2369 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | long method | t | t | t | 0 | 14303 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 2369 | 14303 | ||
| 2369 | YES, I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 14303 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 2369 | 14303 | |
| 2371 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | data class | t | t | t | 0 | 14308 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 1 | 2371 | 14308 | ||
| 2371 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14308 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 2 | 2371 | 14308 |
| 2373 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | long method, data class | t | t | t | long method | 0 | 14312 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 1 | 2373 | 14312 | |
| 2373 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14312 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 2 | 2373 | 14312 |
| 2374 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | data class, long method | t | t | t | long method | 0 | 14314 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 2374 | 14314 | |
| 2374 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 14314 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 2374 | 14314 |
| 2376 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | long method | t | t | t | 0 | 14325 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 2376 | 14325 | ||
| 2376 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14325 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 2376 | 14325 | ||
| 2377 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14326 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 2377 | 14326 |
| 2377 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14326 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 2377 | 14326 | ||
| 2378 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | Long method, 2 Feature envy: | t | f | f | . Long method, 2. Feature envy: | data class | 0 | 14333 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 2 | 2378 | 14333 |
| 2379 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "the bad smells are": [ "Data Class" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | the bad smells are: data class | t | t | t | 0 | 14336 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 1 | 2379 | 14336 | ||
| 2379 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Duplicate code 5. Poor exception handling 6. Inconsistent formatting and naming conventions 7. Low cohesion 8. Lack of comments/documentation 9. Magic numbers/strings used without explanation 10. Complex conditional logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | Long method2 Feature envy3 Primitive obsession4 Duplicate code5 Poor exception handling 6 Inconsistent formatting and naming conventions7 Low cohesion8 Lack of comments/documentation 9 Magic numbers/strings used without explanation | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Duplicate code5. Poor exception handling 6. Inconsistent formatting and naming conventions7. Low cohesion8. Lack of comments/documentation 9. Magic numbers/strings used without explanation | data class | 0 | 14336 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 2 | 2379 | 14336 |
| 2380 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 14337 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2380 | 14337 |
| 2380 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Code duplication, 4. Complex conditional logic, 5. Inconsistent indentation, 6. Lack of comments/documentation, 7. Use of deprecated code, 8. Lack of exception handling, 9. Inefficient error handling using try-catch, 10. Use of block comments instead of line comments, 11. Nested synchronized blocks, 12. Lack of proper resource management using try-finally blocks. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | Long method, 2 Feature envy, 3 Code duplication, 4 Complex conditional logic, 5 Inconsistent indentation, 6 Lack of comments/documentation, 7 Use of deprecated code, 8 Lack of exception handling, 9 Inefficient error handling using try-catch, | t | f | t | . Long method, 3. Code duplication, 4. Complex conditional logic, 5. Inconsistent indentation, 6. Lack of comments/documentation, 7. Use of deprecated code, 8. Lack of exception handling, 9. Inefficient error handling using try-catch, | 0 | 14337 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2380 | 14337 | |
| 2381 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method | t | t | t | 0 | 14338 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2381 | 14338 | ||
| 2381 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inconsistent naming conventions 6. Multiple levels of indentation 7. Unnecessary comments 8. Poor exception handling 9. Unnecessary synchronization 10. Use of best effort instead of handling errors properly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Inconsistent naming conventions6 Multiple levels of indentation7 Unnecessary comments8 Poor exception handling 9 Unnecessary synchronization | t | f | t | 0 | 14338 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2381 | 14338 | ||
| 2387 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14351 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2387 | 14351 | ||
| 2388 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14352 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2388 | 14352 | ||
| 2391 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | long method | t | t | t | 0 | 14362 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 1 | 2391 | 14362 | ||
| 2391 | YES I found bad smells the bad smells are:1.Long method, 2.Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | Long method, 2Primitive obsession | t | f | t | 2.Primitive obsession | 0 | 14362 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 2 | 2391 | 14362 | |
| 2395 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14373 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2395 | 14373 | |
| 2395 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method | t | f | t | 0 | 14373 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2395 | 14373 | ||
| 2396 | {"response": "YES I found bad smells", "bad smells are": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14374 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2396 | 14374 |
| 2396 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14374 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2396 | 14374 | ||
| 2397 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | long method | t | t | t | 0 | 14375 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2397 | 14375 | ||
| 2397 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14375 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2397 | 14375 | ||
| 2398 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2398 | 14376 |
| 2398 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2398 | 14376 | ||
| 2399 | { "message": "YES I found bad smells", "bad smells are": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | 1. data class | t | t | t | 0 | 14378 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 1 | 2399 | 14378 | ||
| 2399 | YES I found bad smells The bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 14378 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 2 | 2399 | 14378 |
| 2400 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | long method, data class | t | t | t | data class | 0 | 14379 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 2400 | 14379 | |
| 2400 | YES I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | Feature envy | t | f | f | Feature envy | long method | 0 | 14379 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 2400 | 14379 |
| 2401 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14380 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 2401 | 14380 | |
| 2401 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Deeply nested code 4. Excessive use of conditionals and boolean checks 5. Lack of proper naming and code documentation 6. Use of multiple if statements instead of a switch statement or polymorphism 7. Inconsistent indentations and formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | Feature envy2 Long method3 Deeply nested code4 Excessive use of conditionals and boolean checks5 Lack of proper naming and code documentation6 Use of multiple if statements instead of a switch statement or polymorphism7 Inconsistent indentations and formatting | t | f | t | 0 | 14380 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 2401 | 14380 | ||
| 2402 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | data class | t | t | t | 0 | 14382 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 1 | 2402 | 14382 | ||
| 2402 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14382 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 2 | 2402 | 14382 |
| 2403 | { "errorMessage": "Please provide the Java code snippet so that I can analyze it for common code smells." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | Not specified | f | f | f | false | 0 | 14383 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 1 | 2403 | 14383 | |
| 2403 | "NO, I did not find any bad smell". | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14383 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 2 | 2403 | 14383 | ||
| 2404 | {"response": "YES I found bad smells the bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | long method | t | t | t | 0 | 14385 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 2404 | 14385 | ||
| 2404 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14385 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 2404 | 14385 | ||
| 2405 | { "message": "YES I found bad smells", "bad_smells": [ { "name": "Long Method" }, { "name": "Feature Envy" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
feature envy | name: long method, name: feature envy | t | t | t | name: long method | 0 | 14386 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 2405 | 14386 | |
| 2405 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14386 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 2405 | 14386 | ||
| 2406 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class without behavior 4. Inappropriate name for entity class 5. Inconsistent formatting and spacing | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy 3 Data class without behavior 4 Inappropriate name for entity class5 Inconsistent formatting and spacing | t | f | t | 0 | 14388 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 2 | 2406 | 14388 | ||
| 2408 | YES, I found bad smells The bad smells are: 1. Long class 2. Long constructor 3. Lack of encapsulation 4. Magic numbers/strings (i.e. 0, 0) 5. Long method 6. Feature envy 7. Inconsistent naming conventions (i.e. both get and set methods are named "readFrom") 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | Long class2 Long constructor3 Lack of encapsulation4 Magic numbers/strings (ie 0, 0)5 Long method6 Feature envy7 Inconsistent naming conventions (ie both get and set methods are named "readFrom")8 Lack of comments/documentation | t | f | f | . Long class2. Long constructor3. Lack of encapsulation4. Magic numbers/strings (i.e. 0, 0)5. Long method6. Feature envy7. Inconsistent naming conventions (i.e. both get and set methods are named "readFrom")8. Lack of comments/documentation | data class | 0 | 14390 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 2408 | 14390 |
| 2414 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Primitive obsession, 6. Object orientation abuser, 7. Inappropriate intimacy, 8. Inappropriate comments, 9. Large class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Primitive obsession, 6 Object orientation abuser, 7 Inappropriate intimacy, 8 Inappropriate comments, 9 Large class | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Primitive obsession, 6. Object orientation abuser, 7. Inappropriate intimacy, 8. Inappropriate comments, 9. Large class | data class | 0 | 14415 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 2414 | 14415 |
| 2416 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | data class, long method | t | t | t | long method | 0 | 14420 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 2416 | 14420 | |
| 2416 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long method\n2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | \n1. long method\n2. feature envy | t | t | f | \\n1. long method\\n2. feature envy | data class | 0 | 14420 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 2416 | 14420 |
| 2418 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14426 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 1 | 2418 | 14426 | |
| 2418 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14426 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 2 | 2418 | 14426 | ||
| 2419 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | 1. long method, feature envy | t | t | t | feature envy | 0 | 14427 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 2419 | 14427 | |
| 2419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the if statement checking for targetType) 4. Null checks 5. Catching throwable instead of specific exception 6. Hardcoding class names and checking for specific class name (String editorName = targetType.getName() + "Editor") 7. Not following naming conventions (targetType instead of targetClass) 8. Use of two return statements within one method (line 10 and line 21) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method2 Feature envy3 Duplicate code (in the if statement checking for targetType)4 Null checks5 Catching throwable instead of specific exception6 Hardcoding class names and checking for specific class name (String editorName = targetTypegetName() + "Editor")7 Not following naming conventions (targetType instead of targetClass)8 Use of two return statements within one method (line | t | f | t | 0 | 14427 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 2419 | 14427 | ||
| 2420 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14428 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 2420 | 14428 |
| 2420 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14428 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 2420 | 14428 | |
| 2421 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | long method, data class | t | t | t | long method | 0 | 14434 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 2421 | 14434 | |
| 2421 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14434 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 2421 | 14434 |
| 2422 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | 1. long method | t | t | t | 0 | 14435 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 2422 | 14435 | ||
| 2422 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Feature envy2 Long method | t | f | t | 0 | 14435 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 2422 | 14435 | ||
| 2423 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | data class | t | t | t | 0 | 14441 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 1 | 2423 | 14441 | ||
| 2423 | YES I found bad smells the bad smells are: 1. Data class 2. Dead code - unused imports and variables 3. Magic numbers - the numbers 3472875885259250934 and 0 are used without explanation 4. Shotgun surgery - several methods directly and indirectly manipulate multiple fields and properties of the class, making it difficult to maintain/change in the future 5. Message chain - the chain of method calls in the equals() method can be simplified for better readability and maintainability | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | Data class2 Dead code - unused imports and variables3 Magic numbers - the numbers 3472875885259250934 and 0 are used without explanation4 Shotgun surgery - several methods directly and indirectly manipulate multiple fields and properties of the class, making it difficult to maintain/change in the future5 Message chain - the chain of method calls in the equals() method can be simplified for better readability and maintainability | t | f | t | making it difficult to maintain/change in the future5. Message chain - the chain of method calls in the equals() method can be simplified for better readability and maintainability | 0 | 14441 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 2423 | 14441 | |
| 2426 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | long method | t | t | t | 0 | 14445 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 2426 | 14445 | ||
| 2426 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Nested conditionals, 4.Method chain, 5.Inappropriate naming, 6.Duplicated code, 7.Complexity, 8.Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method, 2Magic numbers, 3Nested conditionals, 4Method chain, 5Inappropriate naming, 6Duplicated code, 7Complexity, 8Poor exception handling | t | f | t | 2.Magic numbers, 3.Nested conditionals, 4.Method chain, 5.Inappropriate naming, 6.Duplicated code, 7.Complexity, 8.Poor exception handling. | 0 | 14445 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 2426 | 14445 | |
| 2427 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 14446 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 2427 | 14446 |
| 2427 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14446 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 2427 | 14446 | |
| 2431 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14458 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 2431 | 14458 |
| 2431 | with defined inputs. * * * * @param airavataExperimentId * * @param gatewayId * * @param experiment * * "./src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeResourceResource.java" YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14458 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 2431 | 14458 | ||
| 2432 | YES I found bad smells the bad smells are: 1. Data class 2. Long method 3. Setters and getters (they are not necessary in this case) 4. Lack of encapsulation (id and description are public) 5. Primitive obsession (using long and string instead of more specific types) 6. Tight coupling (the class is tied to the @XmlRootElement annotation and cannot easily be replaced) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Data class2 Long method3 Setters and getters (they are not necessary in this case)4 Lack of encapsulation (id and description are public)5 Primitive obsession (using long and string instead of more specific types)6 Tight coupling (the class is tied to the @XmlRootElement annotation and cannot easily be replaced) | t | f | t | 0 | 14460 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 2432 | 14460 | ||
| 2434 | { "YES I found bad smells": "the bad smells are:", "Long method": "The method 'allocateLoadBalancerForNetwork' is too long and should be refactored into smaller methods", "Feature envy": "There are instances where an object envies the features of another object, indicating a potential design issue" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | Incoherent response format, very different from what was expected. | t | t | f | the bad smells are: | data class | 0 | 14462 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 2 | 2434 | 14462 |
| 2435 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14466 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 2435 | 14466 |
| 2438 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | long method, data class | t | t | t | long method | 0 | 14474 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 2438 | 14474 | |
| 2438 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14474 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 2438 | 14474 |
| 2439 | ; YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14478 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 2 | 2439 | 14478 |
| 2442 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14482 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 1 | 2442 | 14482 |
| 2442 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate naming ("DelegatingLayout", "getTargetDecoration", etc.) 3. Feature envy 4. Inconsistent formatting 5. Useless comments 6. Complicated conditionals 7. Too many responsibilities 8. Duplicate code 9. Tight coupling 10. Dependency issues 11. Inefficient object creation 12. Violation of Single Responsibility Principle 13. Lack of modularity 14. Poor variable naming 15. Lack of encapsulation 16. Lack of abstraction 17. Unnecessary code 18. Use of magic numbers 19. Poor exception handling 20. Unnecessary use of interfaces 21. Violation of Law of Demeter (accessing private fields in other classes) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | Long method 2 Inappropriate naming ("DelegatingLayout", "getTargetDecoration", etc) 3 Feature envy 4 Inconsistent formatting 5 Useless comments 6 Complicated conditionals 7 Too many responsibilities 8 Duplicate code 9 Tight coupling | t | f | f | . Long method 2. Inappropriate naming ("DelegatingLayout", "getTargetDecoration", etc.) 3. Feature envy 4. Inconsistent formatting 5. Useless comments 6. Complicated conditionals 7. Too many responsibilities 8. Duplicate code 9. Tight coupling | data class | 0 | 14482 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 2 | 2442 | 14482 |
| 2445 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14492 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 2445 | 14492 |
| 2446 | {"response": "YES, I found bad smells", "bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 14496 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 1 | 2446 | 14496 |
| 2446 | YES I found bad smellsThe bad smells are:1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 14496 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 2 | 2446 | 14496 | ||
| 2447 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | data class, long method | t | t | t | data class | 0 | 14497 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 2447 | 14497 | |
| 2447 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method2 Duplicate code3 Feature Envy | t | f | t | 0 | 14497 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 2447 | 14497 | ||
| 2448 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14498 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 2448 | 14498 |
| 2448 | YES, I found bad smells, the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14498 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 2448 | 14498 | |
| 2449 | { "message": "YES I found bad smells", "detected_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | the bad smells are: long method | t | t | f | the bad smells are: long method | data class | 0 | 14500 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 1 | 2449 | 14500 |
| 2449 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14500 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 2 | 2449 | 14500 |
| 2450 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | long method, data class | t | t | t | data class | 0 | 14505 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2450 | 14505 | |
| 2450 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14505 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2450 | 14505 | |
| 2451 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14506 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2451 | 14506 |
| 2451 | YES I found bad smells bad smells are: 1.Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | Long method, 2 Feature envy | t | f | t | .Long method | 0 | 14506 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2451 | 14506 | |
| 2452 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | long method | t | t | f | long method | data class | 0 | 14514 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 1 | 2452 | 14514 |
| 2452 | YES I found bad smells. the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Inappropriate Naming 5. Data Clumps 6. Shotgun Surgery 7. Divergent Change 8. Large Class 9. Primitive Obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | Long Method2 Feature Envy3 Duplicate Code4 Inappropriate Naming5 Data Clumps6 Shotgun Surgery7 Divergent Change8 Large Class9 Primitive Obsession | t | f | f | . Long Method2. Feature Envy3. Duplicate Code4. Inappropriate Naming5. Data Clumps6. Shotgun Surgery7. Divergent Change8. Large Class9. Primitive Obsession | data class | 0 | 14514 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 2 | 2452 | 14514 |
| 2453 | { "output": "YES I found bad smells. the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | 1. data class | t | t | t | 0 | 14518 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 1 | 2453 | 14518 | ||
| 2453 | YES I found bad smells The bad smells are: 1. Long method 2. Repetitive code 3. Feature envy 4. Primitive obsession 5. Inappropriate intimate accessor 6. Inconsistent naming convention 7. Poor naming 8. Dead code 9. Data class 10. Large class 11. Complex code 12. Shotgun surgery 13. Inappropriate inheritance 14. Refused bequest | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | Long method2 Repetitive code 3 Feature envy 4 Primitive obsession 5 Inappropriate intimate accessor 6 Inconsistent naming convention 7 Poor naming 8 Dead code 9 Data class | t | f | t | 0 | 14518 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 2 | 2453 | 14518 | ||
| 2455 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 14522 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 1 | 2455 | 14522 |
| 2455 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14522 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 2 | 2455 | 14522 |
| 2460 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | long method | t | t | f | long method | data class | 0 | 14540 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 2460 | 14540 |
| 2460 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 14540 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 2460 | 14540 |
| 2461 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | data class, long method | t | t | t | long method | 0 | 14541 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 2461 | 14541 | |
| 2461 | YES I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 14541 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 2461 | 14541 |
| 2463 | COMMENT Sheyi, this is not Java code. But I've still included my feedback below. YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 2463 | 14551 | ||
| 2463 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | long method | t | t | t | 0 | 14551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 2463 | 14551 | ||
| 2464 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | long method | t | t | f | long method | data class | 0 | 14556 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 1 | 2464 | 14556 |
| 2464 | YES I found bad smells: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14556 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 2 | 2464 | 14556 |
| 2465 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | 1. data class | t | t | t | 0 | 14561 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 2465 | 14561 | ||
| 2465 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14561 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 2465 | 14561 |
| 2466 | { "response": "YES I found bad smells", "detected bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14563 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 2466 | 14563 |
| 2466 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14563 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 2466 | 14563 | ||
| 2467 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | data class | t | t | t | 0 | 14568 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 1 | 2467 | 14568 | ||
| 2467 | YES I found bad smells The bad smells are: 1. Unused method 2. Unused variable | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | Unused method2 Unused variable | t | f | f | . Unused method2. Unused variable | data class | 0 | 14568 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 2 | 2467 | 14568 |
| 2468 | <br> YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 14570 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 2 | 2468 | 14570 |
| 2469 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | data class | t | t | t | 0 | 14574 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 1 | 2469 | 14574 | ||
| 2469 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 14574 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 2 | 2469 | 14574 |
| 2470 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14576 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 2470 | 14576 |
| 2471 | { "answer": "YES I found bad smells", "detected_bad_smells": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | data class | t | t | t | 0 | 14578 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 2471 | 14578 | ||
| 2471 | YES I found bad smells The bad smells are: 1. Empty constructor, 2. Insufficient encapsulation, 3. Boolean as a method name. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Empty constructor, 2 Insufficient encapsulation, 3 Boolean as a method name | t | f | f | . Empty constructor, 2. Insufficient encapsulation, 3. Boolean as a method name. | data class | 0 | 14578 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 2471 | 14578 |
| 2474 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 14583 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 1 | 2474 | 14583 |
| 2474 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Exception handling should be improved 5. Inconsistent and unclear naming 6. Code smells related to exception handling (for example, throwing generic exceptions instead of appropriate ones) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
data class | Long method2 Feature envy3 Duplicate code 4 Exception handling should be improved 5 Inconsistent and unclear naming 6 Code smells related to exception handling (for example, throwing generic exceptions instead of appropriate ones) | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Exception handling should be improved 5. Inconsistent and unclear naming 6. Code smells related to exception handling (for example, throwing generic exceptions instead of appropriate ones) | data class | 0 | 14583 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 2 | 2474 | 14583 |
| 2475 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | long method, data class | t | t | t | data class | 0 | 14585 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 1 | 2475 | 14585 | |
| 2475 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | Feature envy | t | f | f | . Feature envy | long method | 0 | 14585 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 2 | 2475 | 14585 |
| 2476 | {"response":"YES I found bad smells","bad smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractGroupingProperty { protected Set columnSet; public AbstractGroupingProperty(Set columnSet) { this.columnSet = columnSet; } public Set getColumnSet() { return columnSet; } // Returns normalized and concise columns from an input column set, by considering // equivalence classes and functional dependencies. protected Set normalizeAndReduceGroupingColumns(Set columns, Map equivalenceClasses, List fds) { Set normalizedColumnSet = getNormalizedColumnsAccordingToEqClasses(columns, equivalenceClasses); reduceGroupingColumns(normalizedColumnSet, fds); return normalizedColumnSet; } // Gets normalized columns, where each column variable is a representative variable of its equivalence class, // therefore, the matching of properties will can consider equivalence classes. private Set getNormalizedColumnsAccordingToEqClasses(Set columns, Map equivalenceClasses) { Set normalizedColumns = new ListSet<>(); if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { normalizedColumns.addAll(columns); return normalizedColumns; } for (LogicalVariable v : columns) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { normalizedColumns.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { normalizedColumns.add(ec.getVariableRepresentative()); } } } return normalizedColumns; } // Using functional dependencies to eliminate unnecessary columns. private void reduceGroupingColumns(Set columnSet, List fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set norm = new ListSet<>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet.retainAll(norm); } } |
data class | long method, data class | t | t | t | long method | 0 | 14587 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java/#L29-L99 | 1 | 2476 | 14587 | |
| 2476 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Unnecessary comments 6. Use of Map instead of more specific data structure 7. Use of null checks 8. Lack of proper indentation and formatting 9. Inefficient algorithms 10. Inadequate variable names 11. Too many public methods 12. Code duplication in the constructors 13. Unnecessary conditional statements 14. Use of primitive types rather than more specific types 15. Missing usage of interfaces or abstract classes 16. Lack of error handling 17. Use of unnecessary data structures 18. Code complexity 19. Lack of clear documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractGroupingProperty { protected Set columnSet; public AbstractGroupingProperty(Set columnSet) { this.columnSet = columnSet; } public Set getColumnSet() { return columnSet; } // Returns normalized and concise columns from an input column set, by considering // equivalence classes and functional dependencies. protected Set normalizeAndReduceGroupingColumns(Set columns, Map equivalenceClasses, List fds) { Set normalizedColumnSet = getNormalizedColumnsAccordingToEqClasses(columns, equivalenceClasses); reduceGroupingColumns(normalizedColumnSet, fds); return normalizedColumnSet; } // Gets normalized columns, where each column variable is a representative variable of its equivalence class, // therefore, the matching of properties will can consider equivalence classes. private Set getNormalizedColumnsAccordingToEqClasses(Set columns, Map equivalenceClasses) { Set normalizedColumns = new ListSet<>(); if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { normalizedColumns.addAll(columns); return normalizedColumns; } for (LogicalVariable v : columns) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { normalizedColumns.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { normalizedColumns.add(ec.getVariableRepresentative()); } } } return normalizedColumns; } // Using functional dependencies to eliminate unnecessary columns. private void reduceGroupingColumns(Set columnSet, List fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set norm = new ListSet<>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet.retainAll(norm); } } |
data class | Long method2 Feature envy3 Duplicate code 4 Inconsistent naming conventions 5 Unnecessary comments 6 Use of Map instead of more specific data structure 7 Use of null checks 8 Lack of proper indentation and formatting 9 Inefficient algorithms | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Inconsistent naming conventions 5. Unnecessary comments 6. Use of Map instead of more specific data structure 7. Use of null checks 8. Lack of proper indentation and formatting 9. Inefficient algorithms | data class | 0 | 14587 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java/#L29-L99 | 2 | 2476 | 14587 |
| 2477 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | long method, data class | t | t | t | long method | 0 | 14589 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 2477 | 14589 | |
| 2478 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14590 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 2478 | 14590 |
| 2480 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | data class, long method | t | t | t | long method | 0 | 14595 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 2480 | 14595 | |
| 2480 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14595 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 2480 | 14595 |
| 2481 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14598 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 2481 | 14598 |
| 2481 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14598 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 2481 | 14598 | |
| 2484 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 14604 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 2484 | 14604 | ||
| 2484 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14604 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 2484 | 14604 |
| 2486 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14610 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 2486 | 14610 | |
| 2486 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 14610 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 2486 | 14610 | ||
| 2487 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Not specified | f | f | f | false | 0 | 14611 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 2487 | 14611 | |
| 2487 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Code complexity 5. Poor naming conventions 6. Inefficient looping 7. Lack of proper commenting or documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Code complexity 5 Poor naming conventions 6 Inefficient looping 7 Lack of proper commenting or documentation | t | f | t | 0 | 14611 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 2487 | 14611 | ||
| 2488 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | 1: data class | t | t | t | 0 | 14613 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 1 | 2488 | 14613 | ||
| 2488 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14613 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 2 | 2488 | 14613 |
| 2489 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | data class, long method | t | t | t | long method | 0 | 14615 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 1 | 2489 | 14615 | |
| 2489 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Magic numbers 4. Deeply nested code 5. Feature envy 6. Inconsistent naming convention 7. Use of static variables and methods 8. Lack of proper comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | Long method2 Long parameter list3 Magic numbers4 Deeply nested code5 Feature envy6 Inconsistent naming convention7 Use of static variables and methods8 Lack of proper comments and documentation | t | f | f | . Long method2. Long parameter list3. Magic numbers4. Deeply nested code5. Feature envy6. Inconsistent naming convention7. Use of static variables and methods8. Lack of proper comments and documentation. | data class | 0 | 14615 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 2 | 2489 | 14615 |
| 2490 | {"message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | data class, long method | t | t | t | long method | 0 | 14617 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 2490 | 14617 | |
| 2490 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Duplicate code 5. Inappropriate commenting 6. Empty method 7. Duplicated code 8. Long parameter list 9. Inappropriate error handling 10. Unnecessary variable 11. Useless constructor 12. Inconsistent naming convention 13. Lazy class 14. Poor exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method2 Feature envy3 Primitive obsession4 Duplicate code5 Inappropriate commenting6 Empty method7 Duplicated code8 Long parameter list9 Inappropriate error handling | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Duplicate code5. Inappropriate commenting6. Empty method7. Duplicated code8. Long parameter list9. Inappropriate error handling | data class | 0 | 14617 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 2490 | 14617 |
| 2493 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | Long method2 Feature Envy 3 Code duplication | t | f | f | . Long method2. Feature Envy 3. Code duplication | data class | 0 | 14624 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 2493 | 14624 |
| 2496 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | long method | t | t | f | long method | data class | 0 | 14641 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 2496 | 14641 |
| 2496 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Empty catch block 4. Boolean trap (conf.getBoolean used to check for an operation) 5. Comments describing what a method should do instead of just doing it 6. Primitive obsession (using strings for host and port values instead of a proper data structure) 7. Magic numbers (use of hardcoded values for server configuration) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | Long method2 Feature envy3 Empty catch block4 Boolean trap (confgetBoolean used to check for an operation)5 Comments describing what a method should do instead of just doing it6 Primitive obsession (using strings for host and port values instead of a proper data structure)7 Magic numbers (use of hardcoded values for server configuration) | t | f | f | . Long method2. Feature envy3. Empty catch block4. Boolean trap (conf.getBoolean used to check for an operation)5. Comments describing what a method should do instead of just doing it6. Primitive obsession (using strings for host and port values instead of a proper data structure)7. Magic numbers (use of hardcoded values for server configuration) | data class | 0 | 14641 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 2496 | 14641 |
| 2497 | { "input": { "code_smells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "java_code": "public class Example { public void doSomething() { // code here } }" }, "output": { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: |
long method | message: yes i found bad smells, detected_bad_smells: 1: long method | t | t | t | message: yes i found bad smells | 0 | 14646 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 1 | 2497 | 14646 | |
| 2497 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Unnecessary variables, 4.Poorly named variables, 5.Inconsistent coding style, 6.Possible null pointer exception, 7.Duplicate code, 8.Hard-coded values, 9.No exception handling, 10.Excessive comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: |
long method | Long method, 2Magic numbers, 3Unnecessary variables, 4Poorly named variables, 5Inconsistent coding style, 6Possible null pointer exception, 7Duplicate code, 8Hard-coded values, 9No exception handling, | t | f | t | 2.Magic numbers, 3.Unnecessary variables, 4.Poorly named variables, 5.Inconsistent coding style, 6.Possible null pointer exception, 7.Duplicate code, 8.Hard-coded values, 9.No exception handling, | 0 | 14646 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 2 | 2497 | 14646 | |
| 2498 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14649 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 1 | 2498 | 14649 | ||
| 2498 | YES I found bad smells the bad smells are: 1. No proper comments or documentation for code. 2. Unclear or misleading variable and method names. 3. Shortened, non-descriptive class name (Customer1131). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | No proper comments or documentation for code2 Unclear or misleading variable and method names3 Shortened, non-descriptive class name (Customer | t | f | f | . No proper comments or documentation for code.2. Unclear or misleading variable and method names.3. Shortened, non-descriptive class name (Customer | data class | 0 | 14649 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 2 | 2498 | 14649 |
| 2499 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | long method, data class | t | t | t | data class | 0 | 14652 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2499 | 14652 | |
| 2499 | YES, I found bad smells the bad smells are: 1.Long method, 2.Unnecessary variable, 3.Magic number, 4.Duplicate code, 5.Inconsistent naming conventions, 6.Feature envy, 7.Inappropriate comments, 8.Unnecessary nesting, 9.Exception handling, 10.Unnecessary null check, 11.Switch statement. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Long method, 2Unnecessary variable, 3Magic number, 4Duplicate code, 5Inconsistent naming conventions, 6Feature envy, 7Inappropriate comments, 8Unnecessary nesting, 9Exception handling, | t | f | t | 2.Unnecessary variable, 3.Magic number, 4.Duplicate code, 5.Inconsistent naming conventions, 6.Feature envy, 7.Inappropriate comments, 8.Unnecessary nesting, 9.Exception handling, | 0 | 14652 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2499 | 14652 | |
| 2500 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14653 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2500 | 14653 |
| 2500 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Error handling mixed with business logic, 5. Excessive comments, 6. Poor exception handling, 7. Code style inconsistencies, 8. Magic numbers, 9. Inefficient use of data structures (e.g. using HashMap instead of List), 10. Poor naming conventions for variables and methods, 11. Complexity and unreadability, 12. Too many nested conditions, 13. Excessive use of context.getProperty(), 14. Poor separation of concerns, 15. Excessive use of session (e.g. session.transfer()), 16. Long parameter list, 17. Lack of encapsulation, 18. Code smells in for loop, 19. Excessive log statements, 20. Not using best practices (e.g. using StringUtils.isBlank instead of StringUtils.isEmpty). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
feature envy | Long method, 2 Feature envy, 3 Duplicate code, 4 Error handling mixed with business logic, 5 Excessive comments, 6 Poor exception handling, 7 Code style inconsistencies, 8 Magic numbers, 9 Inefficient use of data structures (eg using HashMap instead of List), | t | f | t | . Long method, 3. Duplicate code, 4. Error handling mixed with business logic, 5. Excessive comments, 6. Poor exception handling, 7. Code style inconsistencies, 8. Magic numbers, 9. Inefficient use of data structures (e.g. using HashMap instead of List), | 0 | 14653 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2500 | 14653 | |
| 2502 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | data class | t | t | t | 0 | 14662 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 2502 | 14662 | ||
| 2502 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | f | f | f | data class | 0 | 14662 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 2502 | 14662 | ||
| 2503 | { "response": "YES, I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | data class | t | t | t | 0 | 14665 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 1 | 2503 | 14665 | ||
| 2503 | YES I found bad smells the bad smells are: 1. Private variable without getter and setter methods being used | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | Private variable without getter and setter methods being used | t | f | f | . Private variable without getter and setter methods being used | data class | 0 | 14665 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 2 | 2503 | 14665 |
| 2504 | { "answer": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method | t | t | t | 0 | 14666 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2504 | 14666 | ||
| 2504 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method2 Feature Envy | t | f | t | 0 | 14666 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2504 | 14666 | ||
| 2505 | {"result": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14667 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2505 | 14667 |
| 2505 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 14667 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2505 | 14667 |
| 2506 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | long method, data class | t | t | t | long method | 0 | 14669 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 1 | 2506 | 14669 | |
| 2506 | YES, I found bad smells the bad smells are: 1. Getter and setter methods present for a single variable, which can indicate feature envy 2. Lack of readability due to inconsistent indentation 3. The class name and variable name do not follow Java naming conventions 4. The class is declared as static, which may not be necessary 5. Use of a single String variable for an email could potentially lead to issues with validation or formatting in more complex systems. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | Getter and setter methods present for a single variable, which can indicate feature envy2 Lack of readability due to inconsistent indentation3 The class name and variable name do not follow Java naming conventions 4 The class is declared as static, which may not be necessary 5 Use of a single String variable for an email could potentially lead to issues with validation or formatting in more complex systems | t | f | f | . Getter and setter methods present for a single variable, which can indicate feature envy2. Lack of readability due to inconsistent indentation3. The class name and variable name do not follow Java naming conventions 4. The class is declared as static, which may not be necessary 5. Use of a single String variable for an email could potentially lead to issues with validation or formatting in more complex systems. | data class | 0 | 14669 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 2 | 2506 | 14669 |
| 2508 | {"message": "YES I found bad smells", "smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14675 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 1 | 2508 | 14675 | ||
| 2508 | YES, I found bad smells the bad smells are: 1.Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long Method | t | f | f | .Long Method | data class | 0 | 14675 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 2 | 2508 | 14675 |
| 2510 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | data class | t | t | t | 0 | 14684 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 1 | 2510 | 14684 | ||
| 2510 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 14684 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 2 | 2510 | 14684 |
| 2511 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Deprecated methods 5. Redundant comments 6. Poor code organization (lack of clear structure or grouping of methods and variables) 7. Mixed use of tabs and spaces for indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | Long method2 Feature envy3 Commented out code4 Deprecated methods5 Redundant comments6 Poor code organization (lack of clear structure or grouping of methods and variables)7 Mixed use of tabs and spaces for indentation | t | f | f | . Long method2. Feature envy3. Commented out code4. Deprecated methods5. Redundant comments6. Poor code organization (lack of clear structure or grouping of methods and variables)7. Mixed use of tabs and spaces for indentation | data class | 0 | 14687 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 2 | 2511 | 14687 |
| 2512 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14689 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 2512 | 14689 |
| 2513 | { "output": "YES I found bad smells", "detected_code_smells": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 14690 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 1 | 2513 | 14690 |
| 2513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14690 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 2513 | 14690 |
| 2514 | { "output": "YES I found bad smells", "bad smells are:": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | data class | t | t | t | 0 | 14693 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 1 | 2514 | 14693 | ||
| 2514 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14693 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 2 | 2514 | 14693 |
| 2515 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | data class | t | t | t | 0 | 14695 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 1 | 2515 | 14695 | ||
| 2515 | YES, I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14695 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 2 | 2515 | 14695 |
| 2516 | {"message": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | long method | t | t | f | long method | data class | 0 | 14697 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 1 | 2516 | 14697 |
| 2516 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14697 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 2 | 2516 | 14697 |
| 2517 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14699 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 1 | 2517 | 14699 | ||
| 2517 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14699 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 2 | 2517 | 14699 |
| 2518 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | long method, data class | t | t | t | data class | 0 | 14704 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 1 | 2518 | 14704 | |
| 2518 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 14704 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 2 | 2518 | 14704 |
| 2519 | { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 14706 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 2519 | 14706 | |
| 2519 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14706 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 2519 | 14706 | ||
| 2520 | { "message": "YES I found bad smells", "bad smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | 1. long method | t | t | t | 0 | 14709 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 1 | 2520 | 14709 | ||
| 2520 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14709 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 2 | 2520 | 14709 | ||
| 2523 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | long method, data class | t | t | t | data class | 0 | 14713 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 2523 | 14713 | |
| 2523 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14713 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 2523 | 14713 | ||
| 2524 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication within constructor 4. Null check in constructor 5. Inefficient searching method in getProperty() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | Long method2 Feature envy3 Code duplication within constructor4 Null check in constructor5 Inefficient searching method in getProperty() | t | f | f | . Long method2. Feature envy3. Code duplication within constructor4. Null check in constructor5. Inefficient searching method in getProperty() | data class | 0 | 14719 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 2 | 2524 | 14719 |
| 2525 | {"answer": "YES I found bad smells", "detected_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | data class | t | t | t | 0 | 14720 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 2525 | 14720 | ||
| 2525 | YES I found bad smellsThe bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14720 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 2525 | 14720 |
| 2526 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } } |
data class | long method | t | t | f | long method | data class | 0 | 14723 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 | 1 | 2526 | 14723 |
| 2526 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14723 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 | 2 | 2526 | 14723 |
| 2527 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | long method | t | t | t | 0 | 14726 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 2527 | 14726 | ||
| 2527 | YES, I found bad smells the bad smells are: 1. Long method - The method contains a lot of lines and multiple levels of nesting, making it difficult to read and understand. 2. Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Long method - The method contains a lot of lines and multiple levels of nesting, making it difficult to read and understand2 Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method | t | f | t | making it difficult to read and understand.2. Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method. | 0 | 14726 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 2527 | 14726 | |
| 2529 | {"response": "YES I found bad smells", "bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14731 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 1 | 2529 | 14731 |
| 2529 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14731 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 2 | 2529 | 14731 |
| 2530 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
long method | long method | t | t | t | 0 | 14736 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 1 | 2530 | 14736 | ||
| 2530 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14736 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 2 | 2530 | 14736 | |
| 2532 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14744 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 2532 | 14744 | |
| 2532 | YES, I found bad smells. The bad smells are: (1) Long method, (2) Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | ) Long method, (2) Feature envy | t | f | t | (2) Feature envy. | 0 | 14744 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 2532 | 14744 | |
| 2533 | { "output": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14745 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 2533 | 14745 | |
| 2533 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14745 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 2533 | 14745 | ||
| 2534 | {"message": "YES I found bad smells", "bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | data class, long method | t | t | t | long method | 0 | 14749 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 1 | 2534 | 14749 | |
| 2534 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14749 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 2 | 2534 | 14749 |
| 2535 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 14753 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 1 | 2535 | 14753 | ||
| 2535 | YES I found bad smells the bad smells are: 1.Long method, 2.Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | Long method, 2Conditional complexity | t | f | t | 2.Conditional complexity | 0 | 14753 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 2 | 2535 | 14753 | |
| 2539 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14771 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 1 | 2539 | 14771 |
| 2539 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14771 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 2 | 2539 | 14771 | |
| 2540 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14774 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2540 | 14774 | |
| 2540 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14774 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2540 | 14774 | ||
| 2541 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14775 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2541 | 14775 |
| 2541 | YES, I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | Feature envy | t | f | t | 0 | 14775 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2541 | 14775 | ||
| 2542 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | data class | t | t | t | 0 | 14785 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 1 | 2542 | 14785 | ||
| 2542 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14785 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 2 | 2542 | 14785 |
| 2545 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | 1. long method | t | t | t | 0 | 14790 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 2545 | 14790 | ||
| 2545 | YES, I found bad smells The bad smells are: 1. Long method 2. Unnecessary use of boolean flags 3. Mixing of concerns (i.e. handling memory management and file writing in the same method) 4. Magic numbers (i.e. the use of the number 3 in the memory size check) 5. Inconsistent naming conventions (i.e. using both camel case and snake case) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long method2 Unnecessary use of boolean flags3 Mixing of concerns (ie handling memory management and file writing in the same method)4 Magic numbers (ie the use of the number 3 in the memory size check)5 Inconsistent naming conventions (ie using both camel case and snake case) | t | f | t | 0 | 14790 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 2545 | 14790 | ||
| 2546 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 14791 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 2546 | 14791 |
| 2546 | YES I found bad smells 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
feature envy | t | f | f | feature envy | 0 | 14791 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 2546 | 14791 | ||
| 2547 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14792 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 2547 | 14792 |
| 2547 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14792 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 2547 | 14792 | ||
| 2548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | long method, data class | t | t | t | data class | 0 | 14793 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 2548 | 14793 | |
| 2548 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops/cyclomatic complexity 4. Inconsistent indentation 5. Complex conditional statements 6. Magic numbers/unnamed variables 7. Unused/unnecessary variables 8. Lack of comments/documentation 9. Use of null values 10. Large class/object 11. Inefficient use of data structures 12. Code duplication 13. Unclear naming conventions for variables/methods 14. Multiple return statements within a method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long method2 Feature envy3 Nested loops/cyclomatic complexity4 Inconsistent indentation5 Complex conditional statements6 Magic numbers/unnamed variables7 Unused/unnecessary variables 8 Lack of comments/documentation 9 Use of null values | t | f | t | 0 | 14793 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 2548 | 14793 | ||
| 2551 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 14798 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 1 | 2551 | 14798 |
| 2551 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
feature envy | Long method2 Feature envy3 Primitive obsession | t | f | t | 0 | 14798 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 2 | 2551 | 14798 | ||
| 2552 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14803 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 2552 | 14803 |
| 2552 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14803 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 2552 | 14803 | |
| 2555 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | data class | t | t | t | 0 | 14825 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 2555 | 14825 | ||
| 2555 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 14825 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 2555 | 14825 |
| 2558 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14834 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2558 | 14834 | |
| 2558 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 14834 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2558 | 14834 | |
| 2559 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14835 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2559 | 14835 |
| 2559 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14835 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2559 | 14835 | ||
| 2561 | {"response": "YES I found bad smells the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14841 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 1 | 2561 | 14841 |
| 2561 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14841 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 2 | 2561 | 14841 |
| 2562 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | data class, long method | t | t | t | long method | 0 | 14843 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 1 | 2562 | 14843 | |
| 2562 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 14843 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 2 | 2562 | 14843 |
| 2564 | { "response": "YES I found bad smells", "detectedBadSmells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14847 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 1 | 2564 | 14847 | ||
| 2564 | YES I found bad smells. the bad smells are: 1. Magic number 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Magic number2 Feature envy | t | f | f | . Magic number2. Feature envy | data class | 0 | 14847 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 2 | 2564 | 14847 |
| 2565 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | data class | t | t | t | 0 | 14856 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 2565 | 14856 | ||
| 2565 | YES, I found bad smells the bad smells are: 1. No meaningful class name (ExtendedCompletionList) 2. Boolean flag variable (inComplete) 3. Inconsistent indentation 4. Unclear or missing comments 5. No encapsulation of data fields (public access modifiers and direct access to data fields) 6. Lack of constructor overloading (default constructor is unnecessary) 7. Use of raw List type without specifying the type of elements allowed 8. Unused constructor parameter (inComplete) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | No meaningful class name (ExtendedCompletionList)2 Boolean flag variable (inComplete)3 Inconsistent indentation 4 Unclear or missing comments 5 No encapsulation of data fields (public access modifiers and direct access to data fields) 6 Lack of constructor overloading (default constructor is unnecessary) 7 Use of raw List type without specifying the type of elements allowed 8 Unused constructor parameter (inComplete) | t | f | f | . No meaningful class name (ExtendedCompletionList)2. Boolean flag variable (inComplete)3. Inconsistent indentation 4. Unclear or missing comments 5. No encapsulation of data fields (public access modifiers and direct access to data fields) 6. Lack of constructor overloading (default constructor is unnecessary) 7. Use of raw List type without specifying the type of elements allowed 8. Unused constructor parameter (inComplete) | data class | 0 | 14856 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 2565 | 14856 |
| 2567 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | data class | t | t | t | 0 | 14871 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 1 | 2567 | 14871 | ||
| 2567 | YES, I found bad smells 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 14871 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 2 | 2567 | 14871 |
| 2569 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14876 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 2569 | 14876 |
| 2570 | YES, I found bad smells: the bad smells are: 1. Long method 2. Feature envy (the methods in the class are primarily accessing and manipulating instance variables rather than operating on the class itself) 3. Code duplication (duplicate methods for setting and getting errorCode and rpcDataPackage) 4. Lack of encapsulation (all fields are public and directly accessible, without any methods to control access) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | Long method2 Feature envy (the methods in the class are primarily accessing and manipulating instance variables rather than operating on the class itself)3 Code duplication (duplicate methods for setting and getting errorCode and rpcDataPackage)4 Lack of encapsulation (all fields are public and directly accessible, without any methods to control access) | t | f | f | . Long method2. Feature envy (the methods in the class are primarily accessing and manipulating instance variables rather than operating on the class itself)3. Code duplication (duplicate methods for setting and getting errorCode and rpcDataPackage)4. Lack of encapsulation (all fields are public and directly accessible, without any methods to control access) | data class | 0 | 14881 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 2570 | 14881 |
| 2571 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | long method | t | t | t | 0 | 14900 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 2571 | 14900 | ||
| 2571 | YES I found bad smells The bad smells are: 1. Long Method 2. Duplicate Code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long Method2 Duplicate Code3 Feature Envy | t | f | t | 0 | 14900 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 2571 | 14900 | ||
| 2572 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | long method, data class | t | t | t | long method | 0 | 14907 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 1 | 2572 | 14907 | |
| 2572 | YES I found bad smells, the bad smells are: 1.Magic numbers, 2.Data class, 3. Long method, 4.Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | Magic numbers, 2Data class, 3 Long method, 4Feature envy: | t | f | t | .Magic numbers, 3. Long method, 4.Feature envy: | 0 | 14907 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 2 | 2572 | 14907 | |
| 2573 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | long method | t | t | t | 0 | 14908 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 2573 | 14908 | ||
| 2573 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method | t | f | t | 0 | 14908 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 2573 | 14908 | ||
| 2574 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14912 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2574 | 14912 | ||
| 2575 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | 1. long method | t | t | t | 0 | 14915 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2575 | 14915 | ||
| 2575 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14915 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2575 | 14915 | ||
| 2577 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | 1: data class | t | t | t | 0 | 14935 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 1 | 2577 | 14935 | ||
| 2577 | YES I found bad smells #1. Long method #2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | Long method#2 Feature envy | t | f | f | . Long method#2. Feature envy | data class | 0 | 14935 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 2 | 2577 | 14935 |
| 2579 | YES I found bad smells The bad smells are: 1. Duplicate code, 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | Duplicate code, 2 Long method | t | f | f | . Duplicate code, 2. Long method | data class | 0 | 14944 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 2 | 2579 | 14944 |
| 2582 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14956 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 2582 | 14956 | |
| 2582 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14956 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 2582 | 14956 | ||
| 2583 | { "message": "YES I found bad smells", "the bad smells are": [ "3. Feature Envy", "4. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | 3. feature envy, 4. long method | t | t | t | 3. feature envy | 0 | 14963 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2583 | 14963 | |
| 2583 | YES found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14963 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2583 | 14963 | ||
| 2584 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 14973 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 2584 | 14973 |
| 2585 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | data class, long method | t | t | t | long method | 0 | 14976 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 2585 | 14976 | |
| 2585 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicated code - the getProtocol(), getHost(), and isSync() methods are all used to check different variables but have very similar code. Similarly, there is duplicated code in the setter methods. 4. Too many parameters - the constructor and some methods have a lot of parameters passed in. 5. Magic numbers - there are multiple instances where numbers like 10000, 30000, and 16 are used without clear explanation. 6. Inconsistent naming - some variables are named with camel case, while others use underscores. 7. Excessive comments - many of the comments are redundant and add little value to the code. 8. Complex conditionals - some of the if statements contain complex conditions that may be hard to understand and maintain. 9. Inconsistent formatting - there are inconsistencies in formatting, such as uneven indentation. 10. Poor exception handling - in the copy method, an unchecked exception is thrown, which can lead to unexpected behavior. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | Long method2 Feature envy3 Duplicated code - the getProtocol(), getHost(), and isSync() methods are all used to check different variables but have very similar code Similarly, there is duplicated code in the setter methods4 Too many parameters - the constructor and some methods have a lot of parameters passed in5 Magic numbers - there are multiple instances where numbers like | t | f | f | . Long method2. Feature envy3. Duplicated code - the getProtocol(), getHost(), and isSync() methods are all used to check different variables but have very similar code. Similarly, there is duplicated code in the setter methods.4. Too many parameters - the constructor and some methods have a lot of parameters passed in.5. Magic numbers - there are multiple instances where numbers like | data class | 0 | 14976 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 2585 | 14976 |
| 2587 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14990 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2587 | 14990 |
| 2587 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inappropriate comments 5. Lacking encapsulation 6. Inconsistent naming conventions 7. Magic numbers/constants used without explanation 8. Use of legacy code without proper attribution 9. Possible concurrency issues 10. Improper exception handling 11. Lack of modularity/separation of concerns 12. Use of static variables without proper justification 13. Inappropriate levels of abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | Long method2 Feature envy3 Duplicate code4 Inappropriate comments5 Lacking encapsulation6 Inconsistent naming conventions7 Magic numbers/constants used without explanation8 Use of legacy code without proper attribution9 Possible concurrency issues | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inappropriate comments5. Lacking encapsulation6. Inconsistent naming conventions7. Magic numbers/constants used without explanation8. Use of legacy code without proper attribution9. Possible concurrency issues | data class | 0 | 14990 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2587 | 14990 |
| 2588 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | data class | t | t | t | 0 | 14994 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 2588 | 14994 | ||
| 2588 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14994 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 2588 | 14994 |
| 2589 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | data class | t | t | t | 0 | 14996 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 1 | 2589 | 14996 | ||
| 2589 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14996 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 2 | 2589 | 14996 |
| 2590 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | data class, long method | t | t | t | long method | 0 | 14997 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 2590 | 14997 | |
| 2590 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14997 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 2590 | 14997 |
| 2592 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
data class | long method | t | t | f | long method | data class | 0 | 15000 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 1 | 2592 | 15000 |
| 2592 | ### YES I found bad smells 1. Long method 2. Feature envy 3. Primitive obsession 4. Data class 5. Inappropriate use of comments 6. Inconsistent formatting and naming conventions 7. Duplicated code 8. Inefficient data serialization handling 9. Inconsistent use of flags and boolean variables 10. Lack of proper exception handling 11. Unused and unnecessary methods 12. Inappropriate use of transient keyword. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
data class | Long method2 Feature envy3 Primitive obsession4 Data class5 Inappropriate use of comments6 Inconsistent formatting and naming conventions7 Duplicated code8 Inefficient data serialization handling9 Inconsistent use of flags and boolean variables | t | f | t | 0 | 15000 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 2 | 2592 | 15000 | ||
| 2594 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | data class, long method | t | t | t | long method | 0 | 15004 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 2594 | 15004 | |
| 2594 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15004 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 2594 | 15004 |
| 2595 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | long method, data class | t | t | t | long method | 0 | 15005 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 1 | 2595 | 15005 | |
| 2595 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15005 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 2595 | 15005 |
| 2597 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 15009 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 2597 | 15009 | |
| 2597 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 15009 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 2597 | 15009 | ||
| 2598 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15010 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 2598 | 15010 |
| 2598 | Yes, I found bad smells. The bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 15010 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 2598 | 15010 | |
| 2601 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15019 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 2 | 2601 | 15019 |
| 2604 | LFOAbstractType YES I found bad smells the bad smells are: 1.Long method 2.Inappropriate intimacy 3.Magic Number 4.Missing comments 5.Inappropriate abbreviation 6.Bad naming 7.Dead Code 8.Data class 9.Feature envy 10.Incomplete comments 11.Missing final modifier 12.Tradition over Efficiency 13.Confusing naming 14.Large class 15.Lazy Class 16.Magic String 17.Refused bequest 18.Repeated switch 19.Variable length signal 20.Long method chain 21.Speculative Generality 22.Inappropriate type 23.Flat hierarchy 24.Nested method 25.Feature toggle 26.Lazy initialization 27.Method chain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | Long method2Inappropriate intimacy3Magic Number4Missing comments5Inappropriate abbreviation6Bad naming7Dead Code8Data class9Feature envy | t | f | t | 0 | 15026 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 2 | 2604 | 15026 | ||
| 2604 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15026 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 1 | 2604 | 15026 |
| 2605 | {"response": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | data class | t | t | t | 0 | 15028 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 2605 | 15028 | ||
| 2605 | YES I found bad smells: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 15028 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 2605 | 15028 |
| 2606 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15029 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 2606 | 15029 |
| 2606 | YES I found bad smells the bad smells are: 1.Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
feature envy | Long method, 2 Feature envy | t | f | t | .Long method | 0 | 15029 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 2606 | 15029 | |
| 2607 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | long method | t | t | t | 0 | 15030 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 2607 | 15030 | ||
| 2607 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | Long method | t | f | t | 0 | 15030 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 2607 | 15030 | ||
| 2609 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | data class | t | t | t | 0 | 15033 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 1 | 2609 | 15033 | ||
| 2609 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15033 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 2 | 2609 | 15033 |
| 2611 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | long method | t | t | f | long method | data class | 0 | 15040 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 2611 | 15040 |
| 2611 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15040 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 2611 | 15040 |
| 2612 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | f | f | f | data class | 0 | 15042 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 2612 | 15042 | ||
| 2612 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | data class, long method | t | t | t | long method | 0 | 15042 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 2612 | 15042 | |
| 2613 | {"result": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | 1. long method | t | t | t | 0 | 15043 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 2613 | 15043 | ||
| 2613 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 15043 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 2613 | 15043 | ||
| 2614 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | data class, long method | t | t | t | long method | 0 | 15045 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 1 | 2614 | 15045 | |
| 2614 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15045 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 2 | 2614 | 15045 |
| 2616 | {"output": "YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 15048 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 2 | 2616 | 15048 |
| 2616 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15048 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 1 | 2616 | 15048 |
| 2617 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | data class | t | t | t | 0 | 15049 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 2617 | 15049 | ||
| 2617 | YES I found bad smells the bad smells are: 1. Long method 2. Repeating code 3. Feature envy 4. Inconsistent naming conventions 5. Lack of comments 6. Unnecessary comments 7. Tight coupling between classes 8. Violation of single responsibility principle 9. Lack of documentation 10. Unnecessary empty constructors | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | Long method2 Repeating code3 Feature envy4 Inconsistent naming conventions5 Lack of comments6 Unnecessary comments7 Tight coupling between classes8 Violation of single responsibility principle 9 Lack of documentation | t | f | f | . Long method2. Repeating code3. Feature envy4. Inconsistent naming conventions5. Lack of comments6. Unnecessary comments7. Tight coupling between classes8. Violation of single responsibility principle 9. Lack of documentation | data class | 0 | 15049 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 2617 | 15049 |
| 2620 | {"message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | long method | t | t | f | long method | data class | 0 | 15054 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 1 | 2620 | 15054 |
| 2620 | YES I found bad smells. The bad smells are: 1. Duplication of code in the overridden methods. 2. The code has a high level of abstraction which may make it difficult to read and understand. 3. The use of native methods may make the code difficult to maintain and debug. 4. The use of magic numbers in the native method calls. 5. The use of a PrivilegedAction interface without specifying the type of privilege. 6. The use of AccessController without specifying the type of access control. 7. The class name does not accurately describe the purpose of the class. 8. The code violates the Single Responsibility Principle by having multiple methods for setting and getting different options. 9. The code violates the Open-Closed Principle as it is not easily extendable to support new options. 10. The code has low cohesion as the overridden methods all access different native methods. 11. The use of a default constructor which does not initialize any fields or perform any operations. 12. The use of empty catch blocks in the native method calls. 13. The lack of error handling in the native method calls. 14. The use of mutable parameters in the native method calls may lead to unexpected behavior. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Duplication of code in the overridden methods2 The code has a high level of abstraction which may make it difficult to read and understand3 The use of native methods may make the code difficult to maintain and debug4 The use of magic numbers in the native method calls5 The use of a PrivilegedAction interface without specifying the type of privilege6 The use of AccessController without specifying the type of access control7 The class name does not accurately describe the purpose of the class8 The code violates the Single Responsibility Principle by having multiple methods for setting and getting different options9 The code violates the Open-Closed Principle as it is not easily extendable to support new options | t | f | f | . Duplication of code in the overridden methods.2. The code has a high level of abstraction which may make it difficult to read and understand.3. The use of native methods may make the code difficult to maintain and debug.4. The use of magic numbers in the native method calls.5. The use of a PrivilegedAction interface without specifying the type of privilege.6. The use of AccessController without specifying the type of access control.7. The class name does not accurately describe the purpose of the class.8. The code violates the Single Responsibility Principle by having multiple methods for setting and getting different options.9. The code violates the Open-Closed Principle as it is not easily extendable to support new options. | data class | 0 | 15054 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 2 | 2620 | 15054 |
| 2621 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 15056 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 2621 | 15056 |
| 2621 | YES I found bad smells the bad smells are: 1. Long class 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | Long class2 Long method | t | f | f | . Long class2. Long method | data class | 0 | 15056 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 2621 | 15056 |
| 2622 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 15059 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 2622 | 15059 |
| 2622 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 15059 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 2622 | 15059 |
| 2623 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | data class | t | t | t | 0 | 15063 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 2623 | 15063 | ||
| 2623 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 15063 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 2623 | 15063 |
| 2624 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15072 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 2624 | 15072 |
| 2624 | YES, I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicated Code 4. Inconsistent Naming Conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | Long Method 2 Feature Envy 3 Duplicated Code4 Inconsistent Naming Conventions | t | f | f | . Long Method 2. Feature Envy 3. Duplicated Code4. Inconsistent Naming Conventions | data class | 0 | 15072 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 2624 | 15072 |
| 2625 | { "response": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | long method | t | t | f | long method | data class | 0 | 15077 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 1 | 2625 | 15077 |
| 2625 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15077 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 2 | 2625 | 15077 |
| 2626 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 15080 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 1 | 2626 | 15080 | ||
| 2626 | YES I found bad smells the bad smells are: 1. Magic number literal used for generation strategy. 2. Lack of abstraction for repeating code in constructor. 3. String concatenation used in toString() method instead of StringBuilder. 4. Excessive commenting. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Magic number literal used for generation strategy2 Lack of abstraction for repeating code in constructor3 String concatenation used in toString() method instead of StringBuilder4 Excessive commenting | t | f | f | . Magic number literal used for generation strategy.2. Lack of abstraction for repeating code in constructor.3. String concatenation used in toString() method instead of StringBuilder.4. Excessive commenting. | data class | 0 | 15080 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 2 | 2626 | 15080 |
| 2627 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | data class | t | t | t | 0 | 15086 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 1 | 2627 | 15086 | ||
| 2627 | YES I found bad smells. The bad smells are: 1. No documentation provided 2. No error handling or exception handling 3. No comments or explanation of code functionality 4. Instance variables not encapsulated properly 5. Incomplete constructor - requires additional parameters to be fully functional 6. Unclear naming of variables and methods 7. No validation of input parameters in constructor or methods 8. Inconsistent use of modifiers (e.g. final, private, etc.) 9. Inconsistent formatting/style (e.g. using tabs vs. spaces) 10. Duplicate code in superclass and subclass 11. Lack of encapsulation - instance variables are accessed directly in methods 12. No unit tests provided 13. No inheritance hierarchy explained 14. Possible violation of Java naming conventions for class names and interface names 15. Potential for mutable state in instance variables - no setter methods provided to modify values 16. No use of JavaDocs for documenting code 17. Possible violation of Single Responsibility Principle - class appears to have multiple responsibilities 18. Possible violation of Liskov Substitution Principle - subclass may not fully conform to the behavior of superclass 19. No use of public access modifier for interface methods 20. Potential for tight coupling between superclass and subclass. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | No documentation provided2 No error handling or exception handling3 No comments or explanation of code functionality4 Instance variables not encapsulated properly5 Incomplete constructor - requires additional parameters to be fully functional6 Unclear naming of variables and methods7 No validation of input parameters in constructor or methods8 Inconsistent use of modifiers (eg final, private, etc)9 Inconsistent formatting/style (eg using tabs vs spaces) | t | f | f | . No documentation provided2. No error handling or exception handling3. No comments or explanation of code functionality4. Instance variables not encapsulated properly5. Incomplete constructor - requires additional parameters to be fully functional6. Unclear naming of variables and methods7. No validation of input parameters in constructor or methods8. Inconsistent use of modifiers (e.g. final, private, etc.)9. Inconsistent formatting/style (e.g. using tabs vs. spaces) | data class | 0 | 15086 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 2 | 2627 | 15086 |
| 2628 | //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1() { return cGroup_1; } //( public Group getGroup_1_0() { return cGroup_1_0; } //(={BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1_0_0() { return cGroup_1_0_0; } //{BinaryLogicalExpression.lhs=current} public Action getBinaryLogicalExpressionLhsAction_1_0_0_0() { return cBinaryLogicalExpressionLhsAction_1_0_0_0; } //op=LogicalANDOperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //LogicalANDOperator public RuleCall getOpLogicalANDOperatorParserRuleCall_1_0_0_1_0() { return cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseORExpression public RuleCall getRhsBitwiseORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseORExpressionParserRuleCall_1_1_0; } @Override public ParserRule getRule() { return rule; } //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)*; YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Unused code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | () { return cGroup_ | t | f | f | () { return cGroup_ | data class | 0 | 15087 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 2628 | 15087 |
| 2628 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | data class, long method | t | t | t | long method | 0 | 15087 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 2628 | 15087 | |
| 2631 | { "message": "YES I found bad smells", "detected_smells": [ "the bad smells are: 1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | the bad smells are: 1. data class | t | t | t | 0 | 15100 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 1 | 2631 | 15100 | ||
| 2631 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 15100 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 2 | 2631 | 15100 |
| 2632 | YES I found bad smells the bad smells are: 1. Empty constructor 2. Feature envy: the set() method is using EntityReference instead of ReferenceProperty, indicating that the method is more interested in the reference object rather than the property object. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | Empty constructor2 Feature envy: the set() method is using EntityReference instead of ReferenceProperty, indicating that the method is more interested in the reference object rather than the property object | t | f | f | . Empty constructor2. Feature envy: the set() method is using EntityReference instead of ReferenceProperty, indicating that the method is more interested in the reference object rather than the property object. | data class | 0 | 15108 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 2 | 2632 | 15108 |
| 2633 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 15109 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 2633 | 15109 | ||
| 2633 | YES I found bad smells the bad smells are: 1.Long method, 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method, 2Large parameter list, 3Magic numbers, 4Data class, 5Switch statement, 6Duplicate code | t | f | t | 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. | 0 | 15109 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 2633 | 15109 | |
| 2634 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | data class | t | t | t | 0 | 15114 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 2634 | 15114 | ||
| 2634 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15114 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 2634 | 15114 |
| 2639 | { "input_code": "public class Calculator {\n private int number1;\n private int number2;\n\n public Calculator(int number1, int number2) {\n this.number1 = number1;\n this.number2 = number2;\n }\n\n public int add() {\n return number1 + number2;\n }\n\n public int multiply() {\n return number1 * number2;\n }\n}", "code_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | false | 0 | 15142 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2639 | 15142 | ||
| 2639 | . NO, I did not find any bad smells | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 15142 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2639 | 15142 | ||
| 2640 | { "output": "YES, I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | 1. long method | t | t | t | 0 | 15143 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2640 | 15143 | ||
| 2640 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Message chain 5. Unnecessary conditional logic 6. Inconsistent variable naming conventions 7. Use of system exceptions 8. Inappropriate handling of errors or exceptions 9. Mixing of business logic and error handling code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Duplicate code3 Feature envy4 Message chain5 Unnecessary conditional logic6 Inconsistent variable naming conventions7 Use of system exceptions8 Inappropriate handling of errors or exceptions9 Mixing of business logic and error handling code | t | f | t | 0 | 15143 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2640 | 15143 | ||
| 2641 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15144 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2641 | 15144 |
| 2641 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Comments, 4. Magic numbers, 5. Nested if statements, 6. Code duplication, 7. Catching general exceptions, 8. Inconsistent formatting, 9. Inefficient use of conditionals, 10. Unnecessary boolean checks, 11. Lack of abstraction, 12. Inappropriate error handling, 13. Inappropriate logging levels, 14. Poor naming conventions, 15. Inconsistent use of exception types. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | Long method, 2 Feature envy, 3 Comments, 4 Magic numbers, 5 Nested if statements, 6 Code duplication, 7 Catching general exceptions, 8 Inconsistent formatting, 9 Inefficient use of conditionals, | t | f | t | . Long method, 3. Comments, 4. Magic numbers, 5. Nested if statements, 6. Code duplication, 7. Catching general exceptions, 8. Inconsistent formatting, 9. Inefficient use of conditionals, | 0 | 15144 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2641 | 15144 | |
| 2642 | {"message": "YES, I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | data class | t | t | t | 0 | 15145 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 2642 | 15145 | ||
| 2642 | { private int[][] data; public ArrayImageSource( int width, int height ) { super( width, height ); data = new int[width][height]; } public void setPixelRGB(int x, int y, int rgb) { data[x][y] = rgb; } Th "Yes I found bad smells. The bad smells are: 1. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | Feature Envy | t | f | f | . Feature Envy | data class | 0 | 15145 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 2642 | 15145 |
| 2643 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | data class | t | t | t | 0 | 15147 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 2643 | 15147 | ||
| 2643 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15147 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 2643 | 15147 |
| 2644 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15149 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2644 | 15149 |
| 2644 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15149 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2644 | 15149 | ||
| 2645 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method | t | t | t | 0 | 15150 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2645 | 15150 | ||
| 2645 | YES I found bad smells! the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers (".class") 4. Use of abbreviations ("wd", "cr", "cw", "cv", "b", "os", "is", "f", "dt") 5. Lack of proper documentation/commenting 6. Nested if statements and loops 7. Inconsistent formatting and spacing 8. Potential resource leak (input and output streams are not properly handled) 9. Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) 10. Poor variable and method naming 11. Lack of error handling and exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy3 Magic numbers ("class")4 Use of abbreviations ("wd", "cr", "cw", "cv", "b", "os", "is", "f", "dt")5 Lack of proper documentation/commenting6 Nested if statements and loops7 Inconsistent formatting and spacing8 Potential resource leak (input and output streams are not properly handled)9 Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) | t | f | t | "cr", "cw", "cv", "b", "os", "is", "f", "dt")5. Lack of proper documentation/commenting6. Nested if statements and loops7. Inconsistent formatting and spacing8. Potential resource leak (input and output streams are not properly handled)9. Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) | 0 | 15150 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2645 | 15150 | |
| 2646 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | data class, long method | t | t | t | long method | 0 | 15154 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 1 | 2646 | 15154 | |
| 2646 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15154 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 2 | 2646 | 15154 |
| 2647 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | long method | t | t | f | long method | data class | 0 | 15160 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 2647 | 15160 |
| 2647 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 15160 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 2647 | 15160 |
| 2648 | YES I found bad smells. The bad smells are: 1. Long method - connectWithTimeout() 2. Feature envy - connectWithTimeout() and Log(), SysLog(), getPort(), getAddress(), isValid(), isOpen() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TCPSocketChannel { private AsynchronousSocketChannel channel; private String address; private int port; private String logname; /** * Create a TCPSocketChannel that is blocking but times out connects and writes. * @param address The address to connect to. * @param port The port to connect to. 0 value means don't open. * @param logname A name to use for logging. */ public TCPSocketChannel(String address, int port, String logname) { this.address = address; this.port = port; this.logname = logname; try { connectWithTimeout(); } catch (IOException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (ExecutionException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (InterruptedException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (TimeoutException e) { Log(Level.SEVERE, "AsynchronousSocketChannel connectWithTimeout timed out: " + e); } } public int getPort() { return port; } public String getAddress() { return address; } public boolean isValid() { return channel != null; } public boolean isOpen() { return channel.isOpen(); } private void Log(Level level, String message) { TCPUtils.Log(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void SysLog(Level level, String message) { TCPUtils.SysLog(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void connectWithTimeout() throws IOException, ExecutionException, InterruptedException, TimeoutException { if (port == 0) return; InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); Log(Level.INFO, "Attempting to open SocketChannel with InetSocketAddress: " + inetSocketAddress); this.channel = AsynchronousSocketChannel.open(); Future connected = this.channel.connect(inetSocketAddress); connected.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); } public void close() { Log(Level.INFO, "Attempting to close channel."); if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { SysLog(Level.SEVERE, "Failed to close channel: " + e); } } } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @return true if message was successfully sent */ public boolean sendTCPString(String message) { return sendTCPString(message, 0); } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @param retries number of times to retry in event of failure * @return true if message was successfully sent */ public boolean sendTCPString(String message, int retries) { Log(Level.FINE, "About to send: " + message); byte[] bytes = message.getBytes(); return sendTCPBytes(bytes, retries); } /** * Send byte buffer over TCP, including a length header. * * @param buffer the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] buffer) { return sendTCPBytes(buffer, 0); } /** * Send byte buffer over TCP, including a length header. * * @param bytes the bytes to send * @param retries number of times to retry in event of failure * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] bytes, int retries) { try { ByteBuffer header = createHeader(bytes.length); safeWrite(header); ByteBuffer buffer = ByteBuffer.wrap(bytes); safeWrite(buffer); } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e); try { channel.close(); } catch (IOException ioe) { } if (retries > 0) { try { connectWithTimeout(); } catch (Exception connectException) { SysLog(Level.SEVERE, "Failed to reconnect: " + connectException); return false; } return sendTCPBytes(bytes, retries - 1); } return false; } return true; } /** * Send byte buffer over TCP, including a length header. * * @param srcbuffers the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length) { boolean success = false; try { ByteBuffer header = createHeader(length); ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length]; buffers[0] = header; for (int i = 0; i < srcbuffers.length; i++) buffers[i + 1] = srcbuffers[i]; if (TCPUtils.isLogging()) { long t1 = System.nanoTime(); long bytesWritten = write(buffers); long t2 = System.nanoTime(); double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1)); Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s"); } else { write(buffers); } success = true; } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e); try { channel.close(); } catch (IOException ioe) {} } return success; } private ByteBuffer createHeader(int length) { ByteBuffer header = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(length); header.flip(); return header; } private void safeWrite(ByteBuffer buffer) throws InterruptedException, TimeoutException, ExecutionException, IOException { while (buffer.remaining() > 0) { Future future = this.channel.write(buffer); int bytesWritten = future.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (bytesWritten == 0) { throw new IOException("async write failed to send any bytes."); } } } private long write(ByteBuffer[] buffers) throws InterruptedException, TimeoutException, ExecutionException, IOException { long bytesWritten = 0; for (ByteBuffer b : buffers) { bytesWritten += b.remaining(); safeWrite(b); } return bytesWritten; } } |
data class | Long method - connectWithTimeout()2 Feature envy - connectWithTimeout() and Log(), SysLog(), getPort(), getAddress(), isValid(), isOpen() | t | f | f | . Long method - connectWithTimeout()2. Feature envy - connectWithTimeout() and Log(), SysLog(), getPort(), getAddress(), isValid(), isOpen() | data class | 0 | 15162 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/Utils/TCPSocketChannel.java/#L15-L228 | 2 | 2648 | 15162 |
| 2650 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | f | f | f | long method | 0 | 15167 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 2650 | 15167 | ||
| 2651 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | data class, long method | t | t | t | long method | 0 | 15170 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 1 | 2651 | 15170 | |
| 2651 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Feature envy 4. Large class 5. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | Long method 2 Data class3 Feature envy4 Large class5 Shotgun surgery | t | f | t | 0 | 15170 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 2651 | 15170 | ||
| 2652 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | long method | t | t | t | 0 | 15177 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2652 | 15177 | ||
| 2652 | return getCumulativeMemoryWithinPhase(join); YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method 2 Feature envy | t | f | t | 0 | 15177 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2652 | 15177 | ||
| 2653 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 15178 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2653 | 15178 |
| 2653 | return getCumulativeMemoryWithinPhase(join, YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15178 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2653 | 15178 | ||
| 2654 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | data class, long method | t | t | t | long method | 0 | 15180 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 1 | 2654 | 15180 | |
| 2654 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 15180 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 2 | 2654 | 15180 |
| 2655 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | data class, long method | t | t | t | long method | 0 | 15181 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 2655 | 15181 | |
| 2655 | YES I found bad smells the bad smells are: 1. Feature envy: The methods in the UpdateNetworkCmd class access and manipulate properties from other classes, indicating a potential problem with encapsulation. 2. Long method: The execute() method in the UpdateNetworkCmd class is quite long and performs multiple operations, indicating a potential problem with the Single Responsibility Principle. 3. Inconsistent naming convention: In some places, camel case is used to name variables (e.g. changeCidr) while in others, underscores are used (e.g. displayText), indicating a potential problem with consistency. 4. Magic number: There are several instances where specific numbers are used to represent a certain parameter, such as 0, false, or null, which could be replaced with named constants for better readability. 5. Duplicate code: The getId() method is used in multiple places in the UpdateNetworkCmd class, which may indicate a problem with code repetition. 6. Insufficient commenting: Some methods, such as the execute() method, lack thorough comments and documentation, which could make the code harder to understand and maintain. 7. Inconsistent method ordering: The methods in the UpdateNetworkCmd class are not consistently ordered, making it harder to navigate and understand the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Feature envy: The methods in the UpdateNetworkCmd class access and manipulate properties from other classes, indicating a potential problem with encapsulation2 Long method: The execute() method in the UpdateNetworkCmd class is quite long and performs multiple operations, indicating a potential problem with the Single Responsibility Principle3 Inconsistent naming convention: In some places, camel case is used to name variables (eg changeCidr) while in others, underscores are used (eg displayText), indicating a potential problem with consistency4 Magic number: There are several instances where specific numbers are used to represent a certain parameter, such as 0, false, or null, which could be replaced with named constants for better readability5 Duplicate code: The getId() method is used in multiple places in the UpdateNetworkCmd class, which may indicate a problem with code repetition6 Insufficient commenting: Some methods, such as the execute() method, lack thorough comments and documentation, which could make the code harder to understand and maintain7 Inconsistent method ordering: The methods in the UpdateNetworkCmd class are not consistently ordered, making it harder to navigate and understand the code | t | f | f | . Feature envy: The methods in the UpdateNetworkCmd class access and manipulate properties from other classes, indicating a potential problem with encapsulation.2. Long method: The execute() method in the UpdateNetworkCmd class is quite long and performs multiple operations, indicating a potential problem with the Single Responsibility Principle.3. Inconsistent naming convention: In some places, camel case is used to name variables (e.g. changeCidr) while in others, underscores are used (e.g. displayText), indicating a potential problem with consistency.4. Magic number: There are several instances where specific numbers are used to represent a certain parameter, such as 0, false, or null, which could be replaced with named constants for better readability.5. Duplicate code: The getId() method is used in multiple places in the UpdateNetworkCmd class, which may indicate a problem with code repetition.6. Insufficient commenting: Some methods, such as the execute() method, lack thorough comments and documentation, which could make the code harder to understand and maintain.7. Inconsistent method ordering: The methods in the UpdateNetworkCmd class are not consistently ordered, making it harder to navigate and understand the code. | data class | 0 | 15181 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 2655 | 15181 |
| 2656 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | data class | t | t | t | 0 | 15183 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 2656 | 15183 | ||
| 2656 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 15183 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 2656 | 15183 |
| 2658 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 15186 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 2658 | 15186 |
| 2658 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15186 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 2658 | 15186 | ||
| 2660 | { "answer": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SlaveSynchronize { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private volatile String masterAddr = null; public SlaveSynchronize(BrokerController brokerController) { this.brokerController = brokerController; } public String getMasterAddr() { return masterAddr; } public void setMasterAddr(String masterAddr) { this.masterAddr = masterAddr; } public void syncAll() { this.syncTopicConfig(); this.syncConsumerOffset(); this.syncDelayOffset(); this.syncSubscriptionGroupConfig(); } private void syncTopicConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { TopicConfigSerializeWrapper topicWrapper = this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak); if (!this.brokerController.getTopicConfigManager().getDataVersion() .equals(topicWrapper.getDataVersion())) { this.brokerController.getTopicConfigManager().getDataVersion() .assignNewOne(topicWrapper.getDataVersion()); this.brokerController.getTopicConfigManager().getTopicConfigTable().clear(); this.brokerController.getTopicConfigManager().getTopicConfigTable() .putAll(topicWrapper.getTopicConfigTable()); this.brokerController.getTopicConfigManager().persist(); log.info("Update slave topic config from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncTopicConfig Exception, {}", masterAddrBak, e); } } } private void syncConsumerOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { ConsumerOffsetSerializeWrapper offsetWrapper = this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak); this.brokerController.getConsumerOffsetManager().getOffsetTable() .putAll(offsetWrapper.getOffsetTable()); this.brokerController.getConsumerOffsetManager().persist(); log.info("Update slave consumer offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncConsumerOffset Exception, {}", masterAddrBak, e); } } } private void syncDelayOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak); if (delayOffset != null) { String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController .getMessageStoreConfig().getStorePathRootDir()); try { MixAll.string2File(delayOffset, fileName); } catch (IOException e) { log.error("Persist file Exception, {}", fileName, e); } } log.info("Update slave delay offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncDelayOffset Exception, {}", masterAddrBak, e); } } } private void syncSubscriptionGroupConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { SubscriptionGroupWrapper subscriptionWrapper = this.brokerController.getBrokerOuterAPI() .getAllSubscriptionGroupConfig(masterAddrBak); if (!this.brokerController.getSubscriptionGroupManager().getDataVersion() .equals(subscriptionWrapper.getDataVersion())) { SubscriptionGroupManager subscriptionGroupManager = this.brokerController.getSubscriptionGroupManager(); subscriptionGroupManager.getDataVersion().assignNewOne( subscriptionWrapper.getDataVersion()); subscriptionGroupManager.getSubscriptionGroupTable().clear(); subscriptionGroupManager.getSubscriptionGroupTable().putAll( subscriptionWrapper.getSubscriptionGroupTable()); subscriptionGroupManager.persist(); log.info("Update slave Subscription Group from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncSubscriptionGroup Exception, {}", masterAddrBak, e); } } } } |
data class | data class, long method | t | t | t | long method | 0 | 15192 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/slave/SlaveSynchronize.java/#L31-L144 | 1 | 2660 | 15192 | |
| 2660 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SlaveSynchronize { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private volatile String masterAddr = null; public SlaveSynchronize(BrokerController brokerController) { this.brokerController = brokerController; } public String getMasterAddr() { return masterAddr; } public void setMasterAddr(String masterAddr) { this.masterAddr = masterAddr; } public void syncAll() { this.syncTopicConfig(); this.syncConsumerOffset(); this.syncDelayOffset(); this.syncSubscriptionGroupConfig(); } private void syncTopicConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { TopicConfigSerializeWrapper topicWrapper = this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak); if (!this.brokerController.getTopicConfigManager().getDataVersion() .equals(topicWrapper.getDataVersion())) { this.brokerController.getTopicConfigManager().getDataVersion() .assignNewOne(topicWrapper.getDataVersion()); this.brokerController.getTopicConfigManager().getTopicConfigTable().clear(); this.brokerController.getTopicConfigManager().getTopicConfigTable() .putAll(topicWrapper.getTopicConfigTable()); this.brokerController.getTopicConfigManager().persist(); log.info("Update slave topic config from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncTopicConfig Exception, {}", masterAddrBak, e); } } } private void syncConsumerOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { ConsumerOffsetSerializeWrapper offsetWrapper = this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak); this.brokerController.getConsumerOffsetManager().getOffsetTable() .putAll(offsetWrapper.getOffsetTable()); this.brokerController.getConsumerOffsetManager().persist(); log.info("Update slave consumer offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncConsumerOffset Exception, {}", masterAddrBak, e); } } } private void syncDelayOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak); if (delayOffset != null) { String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController .getMessageStoreConfig().getStorePathRootDir()); try { MixAll.string2File(delayOffset, fileName); } catch (IOException e) { log.error("Persist file Exception, {}", fileName, e); } } log.info("Update slave delay offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncDelayOffset Exception, {}", masterAddrBak, e); } } } private void syncSubscriptionGroupConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { SubscriptionGroupWrapper subscriptionWrapper = this.brokerController.getBrokerOuterAPI() .getAllSubscriptionGroupConfig(masterAddrBak); if (!this.brokerController.getSubscriptionGroupManager().getDataVersion() .equals(subscriptionWrapper.getDataVersion())) { SubscriptionGroupManager subscriptionGroupManager = this.brokerController.getSubscriptionGroupManager(); subscriptionGroupManager.getDataVersion().assignNewOne( subscriptionWrapper.getDataVersion()); subscriptionGroupManager.getSubscriptionGroupTable().clear(); subscriptionGroupManager.getSubscriptionGroupTable().putAll( subscriptionWrapper.getSubscriptionGroupTable()); subscriptionGroupManager.persist(); log.info("Update slave Subscription Group from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncSubscriptionGroup Exception, {}", masterAddrBak, e); } } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 15192 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/slave/SlaveSynchronize.java/#L31-L144 | 2 | 2660 | 15192 |
| 2662 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | long method | t | t | f | long method | data class | 0 | 15197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2662 | 15197 |
| 2662 | YES I found bad smells the bad smells are: 1. Long method 2. Data clumps 3. Class data should be private 4. Inappropriate comments 5. Inconsistent indentation 6. Magic numbers (e.g. BUFFER_SIZE = 1500) 7. Unused variables (e.g. buffer, offset) 8. Bad variable naming (e.g. i, ex, addr) 9. Duplicated code (e.g. creating and sending ganglia messages has duplicate code) 10. Inconsistent use of access modifiers 11. Multiple responsibilities (GangliaServer has the responsibilities of creating ganglia messages and sending them, but also implementing the MonitorService interface) 12. Long parameter list (the configure method has too many parameters) 13. Use of deprecated code (e.g. getLogger and warn) 14. Empty catch blocks 15. Nested if statements 16. Mixing different styles of error handling (exceptions and return values) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | Long method 2 Data clumps 3 Class data should be private 4 Inappropriate comments 5 Inconsistent indentation 6 Magic numbers (eg BUFFER_SIZE = | t | f | f | . Long method 2. Data clumps 3. Class data should be private 4. Inappropriate comments 5. Inconsistent indentation 6. Magic numbers (e.g. BUFFER_SIZE = | data class | 0 | 15197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2662 | 15197 |
| 2664 | { "response": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 15200 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 1 | 2664 | 15200 |
| 2664 | YES I found bad smells the bad smells are: 1. Long method 2. Multiple if/else blocks without proper abstraction 3. Inconsistent indentation and code formatting 4. Lack of comments and documentation for the purpose of the method and parameters 5. Mixed use of instanceOf and casting in the condition 6. Hardcoded values and magic numbers for exceptions and return values | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
feature envy | Long method2 Multiple if/else blocks without proper abstraction3 Inconsistent indentation and code formatting4 Lack of comments and documentation for the purpose of the method and parameters5 Mixed use of instanceOf and casting in the condition6 Hardcoded values and magic numbers for exceptions and return values | t | f | f | . Long method2. Multiple if/else blocks without proper abstraction3. Inconsistent indentation and code formatting4. Lack of comments and documentation for the purpose of the method and parameters5. Mixed use of instanceOf and casting in the condition6. Hardcoded values and magic numbers for exceptions and return values | feature envy | 0 | 15200 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 2 | 2664 | 15200 |
| 2665 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | the bad smells are: long method | t | t | f | the bad smells are: long method | data class | 0 | 15202 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 2665 | 15202 |
| 2665 | YES I found bad smells the bad smells are: 1. Code duplication 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | Code duplication2 Long method 3 Feature envy | t | f | f | . Code duplication2. Long method 3. Feature envy | data class | 0 | 15202 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 2665 | 15202 |
| 2666 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | long method | t | t | t | 0 | 15203 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 2666 | 15203 | ||
| 2666 | YES, I found bad smellsthe bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method | t | f | t | 0 | 15203 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 2666 | 15203 | ||
| 2667 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15204 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 2667 | 15204 |
| 2667 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long method", "2. Duplicate code"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
feature envy | 1. long method, 2. duplicate code | t | t | f | 1. long method, 2. duplicate code | feature envy | 0 | 15204 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 2667 | 15204 |
| 2670 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | long method | t | t | t | 0 | 15211 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2670 | 15211 | ||
| 2670 | public class CodeChecker { YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method2 Feature envy | t | f | t | 0 | 15211 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2670 | 15211 | ||
| 2671 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15212 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2671 | 15212 |
| 2671 | public boolean isAlgParams() { return getCertificate().getPublicKey().getEncodedParams() != null; YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15212 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2671 | 15212 | ||
| 2672 | YES I found bad smells The bad smells are: 1. Long methods (methods that could potentially be broken down into smaller, more specific methods for increased readability and maintainability). 2. Feature envy (methods that access and manipulate data from other classes, indicating a potential lack of encapsulation and cohesion). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | Long methods (methods that could potentially be broken down into smaller, more specific methods for increased readability and maintainability)2 Feature envy (methods that access and manipulate data from other classes, indicating a potential lack of encapsulation and cohesion) | t | f | f | . Long methods (methods that could potentially be broken down into smaller, more specific methods for increased readability and maintainability).2. Feature envy (methods that access and manipulate data from other classes, indicating a potential lack of encapsulation and cohesion). | data class | 0 | 15216 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 2672 | 15216 |
| 2673 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | long method | t | t | t | 0 | 15225 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2673 | 15225 | ||
| 2673 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method2 Feature envy | t | f | t | 0 | 15225 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2673 | 15225 | ||
| 2674 | // 5. Input optimisation YES I found bad smells 1. Long method 2. Unused code (deprecated oldAlgo variable) 3. Duplicate code/feature envy (repetitive use of algoUtils.computeBucketMapJoinCPUCost and algoUtils.computeBucketMapJoinIOCost) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | Long method2 Unused code (deprecated oldAlgo variable)3 Duplicate code/feature envy (repetitive use of algoUtilscomputeBucketMapJoinCPUCost and algoUtilscomputeBucketMapJoinIOCost) | t | f | t | 0 | 15226 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2674 | 15226 | ||
| 2674 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15226 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2674 | 15226 |
| 2675 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | data class | t | t | t | 0 | 15229 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 2675 | 15229 | ||
| 2675 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data clump 4. Large class 5. Primitive obsession 6. Lazy element 7. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | Long method2 Feature envy3 Data clump4 Large class5 Primitive obsession6 Lazy element7 Inappropriate intimacy | t | f | f | . Long method2. Feature envy3. Data clump4. Large class5. Primitive obsession6. Lazy element7. Inappropriate intimacy | data class | 0 | 15229 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 2675 | 15229 |
| 2678 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | long method | t | t | t | 0 | 15253 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2678 | 15253 | ||
| 2678 | YES, I found bad smells. the bad smells are: 1. Long method 2. Commented out code 3. Useless if statement 4. Duplicated code 5. Inconsistent naming convention (camelCase and lowercase) 6. Magic number (0 in the if statement) 7. Feature envy (mailToAddresses and mailHost variables are called multiple times) 8. Mixing of responsibilities (sending email and error handling in the same method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Commented out code3 Useless if statement4 Duplicated code5 Inconsistent naming convention (camelCase and lowercase)6 Magic number (0 in the if statement)7 Feature envy (mailToAddresses and mailHost variables are called multiple times)8 Mixing of responsibilities (sending email and error handling in the same method) | t | f | t | 0 | 15253 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2678 | 15253 | ||
| 2679 | YES I found bad smells Bad smells are: 1. Long method 2. Feature envy 3. Variable name not descriptive 4. Magic number 5. Duplicated code 6. Catching broad exception types 7. Inconsistent formatting and indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | Long method2 Feature envy3 Variable name not descriptive4 Magic number5 Duplicated code6 Catching broad exception types7 Inconsistent formatting and indentation | t | f | t | 0 | 15254 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2679 | 15254 | ||
| 2682 | {"message": "YES, I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 15268 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 2 | 2682 | 15268 |
| 2682 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | data class | 0 | 15268 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 2682 | 15268 |
| 2683 | */ YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 15269 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 2683 | 15269 | ||
| 2684 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 15270 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 2684 | 15270 |
| 2684 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15270 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 2684 | 15270 | ||
| 2687 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15282 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 2687 | 15282 |
| 2687 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | Feature envy2 Long method | t | f | t | 0 | 15282 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 2687 | 15282 | ||
| 2689 | { "message": "YES I found bad smells" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | Not specified | f | f | f | "YES I found bad smells" } | false | 0 | 15284 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 2689 | 15284 |
| 2689 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | data class, long method | t | t | t | long method | 0 | 15284 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 2689 | 15284 | |
| 2691 | { "output": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Data Class" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | 1: data class, 2: long method | t | t | t | 2: long method | 0 | 15300 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 1 | 2691 | 15300 | |
| 2691 | YES I found bad smells the bad smells are: 1. Parameter list 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | Parameter list 2 Long method 3 Feature envy | t | f | f | . Parameter list 2. Long method 3. Feature envy | data class | 0 | 15300 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 2 | 2691 | 15300 |
| 2696 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method, data class | t | t | t | data class | 0 | 15319 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2696 | 15319 | |
| 2696 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 15319 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2696 | 15319 | ||
| 2697 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15320 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2697 | 15320 |
| 2697 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Complex conditional statements 4. Nested loops 5. Multiple return statements 6. Lack of proper exception handling 7. Hard-coded values 8. Poorly named variables and methods 9. Mixing of concerns - the method is responsible for both weaving and writing to files 10. Inefficient usage of resources - opening and closing input/output streams for each file. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | Long method2 Feature envy3 Complex conditional statements4 Nested loops5 Multiple return statements6 Lack of proper exception handling7 Hard-coded values8 Poorly named variables and methods9 Mixing of concerns - the method is responsible for both weaving and writing to files | t | f | t | 0 | 15320 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2697 | 15320 | ||
| 2699 | { "output": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, data class | t | t | t | data class | 0 | 15326 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 2699 | 15326 | |
| 2699 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 15326 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 2699 | 15326 | ||
| 2703 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code, 3. Indecent exposure, 4. Inappropriate intimacy, 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2 Duplicate code, 3 Indecent exposure, 4 Inappropriate intimacy, 5 Feature envy | t | f | t | 2. Duplicate code, 3. Indecent exposure, 4. Inappropriate intimacy, 5. Feature envy | 0 | 15335 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 2703 | 15335 | |
| 2704 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | long method | t | t | f | long method | data class | 0 | 15338 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 2704 | 15338 |
| 2704 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15338 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 2704 | 15338 |
| 2706 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15347 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 2706 | 15347 |
| 2706 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15347 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 2706 | 15347 |
| 2734 | { "code": [ "public class OrderItem {", " private String itemName;", " private int quantity;", "", " public OrderItem(String itemName, int quantity) {", " this.itemName = itemName;", " this.quantity = quantity;", " }", "", " public double calculateTotalPrice(double itemPrice) {", " return this.quantity * itemPrice;", " }", "}" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | Not specified | f | f | f | false | 0 | 710 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L45156-L45191 | 1 | 2734 | 710 | |
| 2734 | of the above will apply, the code is too straightforward to be considered bad smells. NO, I did not find any bad smells: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 710 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L45156-L45191 | 2 | 2734 | 710 | ||
| 2748 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | 1. long method | t | t | t | 0 | 804 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 2748 | 804 | ||
| 2748 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Poor exception handling 4. Use of magic numbers 5. Lack of proper commenting/documentation 6. Unnecessary nesting in switch statement 7. Unnecessary use of mutable fields 8. Potential for memory leaks through use of mutable fields without proper resetting before return statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Feature envy3 Poor exception handling4 Use of magic numbers5 Lack of proper commenting/documentation6 Unnecessary nesting in switch statement7 Unnecessary use of mutable fields 8 Potential for memory leaks through use of mutable fields without proper resetting before return statements | t | f | t | 0 | 804 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 2748 | 804 | ||
| 2750 | YES I found bad smells 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 818 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 2750 | 818 | ||
| 2759 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private BundleEvent initializeEvent(Bundle bundle) { switch (bundle.getState()) { case Bundle.INSTALLED: return new BundleEvent(BundleEvent.INSTALLED, bundle); case Bundle.RESOLVED: return new BundleEvent(BundleEvent.RESOLVED, bundle); default: return new BundleEvent(BundleEvent.STARTED, bundle); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 874 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.providers/src/main/java/org/eclipse/smarthome/automation/internal/core/provider/AutomationResourceBundlesTracker.java/#L278-L287 | 1 | 2759 | 874 |
| 2759 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private BundleEvent initializeEvent(Bundle bundle) { switch (bundle.getState()) { case Bundle.INSTALLED: return new BundleEvent(BundleEvent.INSTALLED, bundle); case Bundle.RESOLVED: return new BundleEvent(BundleEvent.RESOLVED, bundle); default: return new BundleEvent(BundleEvent.STARTED, bundle); } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 874 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.providers/src/main/java/org/eclipse/smarthome/automation/internal/core/provider/AutomationResourceBundlesTracker.java/#L278-L287 | 2 | 2759 | 874 | |
| 2771 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | long method | t | t | f | long method | data class | 0 | 1068 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 2771 | 1068 |
| 2771 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | Long method2 Duplicate code | t | f | f | . Long method2. Duplicate code | data class | 0 | 1068 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 2771 | 1068 |
| 2781 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | long method | t | t | t | 0 | 1122 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2781 | 1122 | ||
| 2781 | public boolean paramsLacking() { return pkixParams.getAnyPolicyInhibited() || pkixParams.getPolicyMappingInhibited() || pkixParams.isExplicitPolicyRequired() || pkixParams.isPolicyMappingInhibited() || pkixParams.isAnyPolicyInhibited() || !pkixParams.getPolicyQualifiersRejected() || !pkixParams.getInitialPolicies().isEmpty(); } YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Primitive obsession 5. Inappropriate intimacy 6. Inconsistent naming 7. Temporary field 8. Comments 9. Shotgun surgery 10. Lazy class 11. Data class 12. Data clumps 13. Speculative generality 14. Message chains 15. Brain overload 16. Large class 17. Deficient encapsulation 18. Combinatorial explosion 19. Extensive coupling 20. Divergent change 21. Inappropriate subclass 22. Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method 2 Feature envy 3 Duplicate code 4 Primitive obsession 5 Inappropriate intimacy 6 Inconsistent naming 7 Temporary field 8 Comments 9 Shotgun surgery | t | f | t | 0 | 1122 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2781 | 1122 | ||
| 2796 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | f | f | f | data class | 0 | 1230 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 2 | 2796 | 1230 | ||
| 2796 | { "response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 1230 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 1 | 2796 | 1230 | |
| 2822 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | 1. long method | t | t | t | 0 | 1499 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 2822 | 1499 | ||
| 2822 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 1499 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 2822 | 1499 | ||
| 2841 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
long method | long method | t | t | t | 0 | 1663 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 2841 | 1663 | ||
| 2841 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
long method | Long method2 Feature envy | t | f | t | 0 | 1663 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 2841 | 1663 | ||
| 2851 | YES I found bad smells the bad smells are: 1. Unused import 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getDisplayName() { return AssignmentsTestLanguageLanguage.INSTANCE.getDisplayName(); } |
feature envy | Unused import 2 Feature Envy | t | f | t | 0 | 1807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.core.idea.tests/src-gen/org/eclipse/xtext/parser/assignments/idea/highlighting/AssignmentsTestLanguageBaseColorSettingsPage.java/#L13-L16 | 2 | 2851 | 1807 | ||
| 2863 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 1961 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/thrift/ClientService.java/#L33559-L33561 | 2 | 2863 | 1961 | ||
| 2863 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 1961 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/thrift/ClientService.java/#L33559-L33561 | 1 | 2863 | 1961 | ||
| 2865 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | data class | t | t | t | 0 | 1975 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 1 | 2865 | 1975 | ||
| 2865 | YES, I found bad smells. The bad smells are: 1. No comments or documentation present. 2. Inconsistent indentation and formatting. 3. Unused imports. 4. Unnecessary use of serializable. 5. Lack of validation for getTargetRepositoryId() and setTargetRepositoryId() methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | No comments or documentation present2 Inconsistent indentation and formatting3 Unused imports4 Unnecessary use of serializable5 Lack of validation for getTargetRepositoryId() and setTargetRepositoryId() methods | t | f | f | . No comments or documentation present.2. Inconsistent indentation and formatting.3. Unused imports.4. Unnecessary use of serializable.5. Lack of validation for getTargetRepositoryId() and setTargetRepositoryId() methods. | data class | 0 | 1975 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 2 | 2865 | 1975 |
| 2872 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | long method | t | t | f | long method | feature envy | 0 | 2003 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 1 | 2872 | 2003 |
| 2872 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 2003 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 2 | 2872 | 2003 | ||
| 2886 | {"response":"YES I found bad smells","the bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | data class | t | t | t | 0 | 2054 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 2886 | 2054 | ||
| 2886 | { "YES I found bad smells": true, "the bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 2054 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 2 | 2886 | 2054 |
| 2899 | { "input": { "codeSmellsToCheck": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "javaCode": "public class Example { private int calculateSomething(int a, int b) { int result = a + b; if (result > 100) { return 100; } else { return result; } } private void printResult(int result) { System.out.println(result); } }" }, "output": { "message": "YES I found bad smells", "detectedCodeSmells": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | message: yes i found bad smells, detectedcodesmells: long method | t | t | f | message: yes i found bad smells, detectedcodesmells: long method | data class | 0 | 2138 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 1 | 2899 | 2138 |
| 2899 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 2138 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 2 | 2899 | 2138 | ||
| 2901 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | long method, data class | t | t | t | data class | 0 | 2195 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 2901 | 2195 | |
| 2901 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy - The method is accessing variables from a different class, indicating that it may not be the best class to handle this functionality. 3. Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case. 4. Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods. 5. Large class - The class may have too many responsibilities and could be split into smaller, more focused classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method2 Feature envy - The method is accessing variables from a different class, indicating that it may not be the best class to handle this functionality3 Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case4 Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods5 Large class - The class may have too many responsibilities and could be split into smaller, more focused classes | t | f | t | indicating that it may not be the best class to handle this functionality.3. Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case.4. Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods.5. Large class - The class may have too many responsibilities and could be split into smaller, more focused classes. | 0 | 2195 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 2901 | 2195 | |
| 2914 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | 1. data class | t | t | t | 0 | 2250 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 1 | 2914 | 2250 | ||
| 2914 | YES I found bad smells the bad smells are: 1. Data Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | Data Class | t | f | t | 0 | 2250 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 2 | 2914 | 2250 | ||
| 2915 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | long method | t | t | t | 0 | 2253 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 1 | 2915 | 2253 | ||
| 2915 | YES I found bad smells the bad smells are: 1. Long method 2. Repeated code (saveState) 3. Feature envy (multiple method calls on different objects) 4. Inefficient use of flag variables 5. Unused code (clearAttributes() not currently necessary) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | Long method2 Repeated code (saveState)3 Feature envy (multiple method calls on different objects)4 Inefficient use of flag variables5 Unused code (clearAttributes() not currently necessary) | t | f | t | 0 | 2253 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 2 | 2915 | 2253 | ||
| 2965 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | data class, long method | t | t | t | long method | 0 | 2728 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 1 | 2965 | 2728 | |
| 2965 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Lack of cohesion 4. Redundant code (e.g. the constructor and get methods for validBits and value) 5. No use of encapsulation (all fields are public) 6. Violation of single responsibility principle (the OptionSet class has both encoding and decoding methods) 7. Code duplication (the code for encoding and decoding is repeated in the inner Codec class) 8. Poor naming conventions (e.g. getType() method in the Codec class could be named more descriptively) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | Long method2 Feature envy3 Lack of cohesion4 Redundant code (eg the constructor and get methods for validBits and value)5 No use of encapsulation (all fields are public)6 Violation of single responsibility principle (the OptionSet class has both encoding and decoding methods)7 Code duplication (the code for encoding and decoding is repeated in the inner Codec class)8 Poor naming conventions (eg getType() method in the Codec class could be named more descriptively) | t | f | f | . Long method2. Feature envy3. Lack of cohesion4. Redundant code (e.g. the constructor and get methods for validBits and value)5. No use of encapsulation (all fields are public)6. Violation of single responsibility principle (the OptionSet class has both encoding and decoding methods)7. Code duplication (the code for encoding and decoding is repeated in the inner Codec class)8. Poor naming conventions (e.g. getType() method in the Codec class could be named more descriptively) | data class | 0 | 2728 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 2 | 2965 | 2728 |
| 3002 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | 1. data class | t | t | t | 0 | 3071 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 1 | 3002 | 3071 | ||
| 3002 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 3071 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 2 | 3002 | 3071 |
| 3053 | {"response": "YES I found bad smells the bad smells are:1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 3501 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 3053 | 3501 |
| 3053 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy (multiple references to sysDiagnostics) 4. Primitive obsession (repeated use of FormatUtils methods) 5. Switch statement (multiple entries and use of Map for sysDiagnostics properties) 6. Magic numbers (repeated use of -1) 7. Excessive parameters (sysDiagnostics and createStorageUsageDTO methods) 8. Inappropriate intimacy (accessing sysDiagnostics properties directly) 9. Lack of encapsulation (exposing internal details of SystemDiagnostics and creating StorageUsageDTO objects outside of class) 10. Data class (SystemDiagnostics, SystemDiagnosticsDTO, SystemDiagnosticsSnapshotDTO all contain only properties and getters/setters) 11. Large class (containing multiple methods and properties) 12. Primitive coupling (directly referencing sysDiagnostics rather than through an abstraction) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long method2 Duplicate code3 Feature envy (multiple references to sysDiagnostics)4 Primitive obsession (repeated use of FormatUtils methods)5 Switch statement (multiple entries and use of Map for sysDiagnostics properties)6 Magic numbers (repeated use of - | t | f | t | 0 | 3501 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 3053 | 3501 | ||
| 3075 | {"response": "YES I found bad smells", "bad smells": ["Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public InstrumentationFacility getInstrumentationFacility() { return getRootContext().getInstrumentationFacility(); } |
feature envy | feature envy, long method | t | t | t | long method | 0 | 3714 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-core/src/main/java/org/apache/uima/impl/ChildUimaContext_impl.java/#L101-L103 | 1 | 3075 | 3714 | |
| 3075 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public InstrumentationFacility getInstrumentationFacility() { return getRootContext().getInstrumentationFacility(); } |
feature envy | Feature envy | t | f | t | 0 | 3714 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-core/src/main/java/org/apache/uima/impl/ChildUimaContext_impl.java/#L101-L103 | 2 | 3075 | 3714 | ||
| 3145 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4282 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 3145 | 4282 |
| 3145 | YES I found bad smells The bad smells are: 1. Long method 2. No attributes 3. Feature envy 4. Use of raw types 5. Use of primitive type instead of objects 6. Code duplication 7. Lack of proper commenting/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 No attributes3 Feature envy4 Use of raw types5 Use of primitive type instead of objects6 Code duplication7 Lack of proper commenting/documentation | t | f | f | . Long method2. No attributes3. Feature envy4. Use of raw types5. Use of primitive type instead of objects6. Code duplication7. Lack of proper commenting/documentation | data class | 0 | 4282 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 3145 | 4282 |
| 3200 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 4807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 1 | 3200 | 4807 | ||
| 3200 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 4807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 2 | 3200 | 4807 | ||
| 3215 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 5113 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 2 | 3215 | 5113 |
| 3215 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 5113 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 1 | 3215 | 5113 |
| 3236 | {"response":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 5427 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 2 | 3236 | 5427 |
| 3236 | { "result": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
data class | long method, data class | t | t | t | long method | 0 | 5427 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 1 | 3236 | 5427 | |
| 3238 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5441 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 1 | 3238 | 5441 |
| 3238 | YES, I found bad smells: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 5441 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 2 | 3238 | 5441 |
| 3290 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 5783 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 3290 | 5783 | |
| 3290 | YES, I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | Feature envy | t | f | t | 0 | 5783 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 3290 | 5783 | ||
| 3331 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6212 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 1 | 3331 | 6212 |
| 3334 | {"message": "YES I found bad smells, the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | 1. long method | t | t | t | 0 | 6247 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 3334 | 6247 | ||
| 3334 | YES I found bad smells,the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6247 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 3334 | 6247 | ||
| 3348 | {"response": "YES I found bad smells", "detected bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6306 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 3348 | 6306 |
| 3348 | YES I found bad smells. The bad smells are: Feature envy, Long method, Duplicate code, Complex method, Unnecessary comments, Indecent exposure, Inappropriate intimacy, Switch statement, Magic numbers, Primitive obsession, God class, Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
feature envy | Feature envy, Long method, Duplicate code, Complex method, Unnecessary comments, Indecent exposure, Inappropriate intimacy, Switch statement, Magic numbers, Primitive obsession, God class, Lazy class | t | f | t | Long method, Duplicate code, Complex method, Unnecessary comments, Indecent exposure, Inappropriate intimacy, Switch statement, Magic numbers, Primitive obsession, God class, Lazy class | 0 | 6306 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 3348 | 6306 | |
| 3358 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected String getTableStatus( Statement sStatement ) throws SQLException { ResultSet statusResultSet = sStatement.executeQuery( "show table status" ); StringBuilder statusString = new StringBuilder(); int numColumns = statusResultSet.getMetaData().getColumnCount(); while ( statusResultSet.next() ) { statusString.append( "\n" ); for ( int i = 1; i <= numColumns; i++ ) { statusString.append( statusResultSet.getMetaData().getColumnLabel( i ) + " [" + statusResultSet.getString( i ) + "] | " ); } } return statusString.toString(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6369 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java/#L212-L228 | 1 | 3358 | 6369 |
| 3358 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected String getTableStatus( Statement sStatement ) throws SQLException { ResultSet statusResultSet = sStatement.executeQuery( "show table status" ); StringBuilder statusString = new StringBuilder(); int numColumns = statusResultSet.getMetaData().getColumnCount(); while ( statusResultSet.next() ) { statusString.append( "\n" ); for ( int i = 1; i <= numColumns; i++ ) { statusString.append( statusResultSet.getMetaData().getColumnLabel( i ) + " [" + statusResultSet.getString( i ) + "] | " ); } } return statusString.toString(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6369 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java/#L212-L228 | 2 | 3358 | 6369 | ||
| 3367 | I did not find any bad smells. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 6393 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 3367 | 6393 | ||
| 3367 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 6393 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 3367 | 6393 | ||
| 3368 | { "input_code": "public class Calculator {\n public int add(int a, int b) {\n return a + b;\n }\n\n public int subtract(int a, int b) {\n return a - b;\n }\n\n public int multiply(int a, int b) {\n return a * b;\n }\n}", "code_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | Long Method, Data Class | false | 0 | 6394 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 3368 | 6394 | |
| 3368 | . NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 6394 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 3368 | 6394 | ||
| 3381 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | 1. long method | t | t | t | 0 | 6543 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 3381 | 6543 | ||
| 3381 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6543 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 3381 | 6543 | ||
| 3389 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6567 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 3389 | 6567 |
| 3389 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6567 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 3389 | 6567 | ||
| 3396 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | 1. long method | t | t | t | 0 | 6591 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 3396 | 6591 | ||
| 3396 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6591 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 3396 | 6591 | ||
| 3412 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 6662 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 1 | 3412 | 6662 | ||
| 3412 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Hard-coded strings 4. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Magic numbers3 Hard-coded strings4 Code duplication | t | f | t | 0 | 6662 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 2 | 3412 | 6662 | ||
| 3437 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6831 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 2 | 3437 | 6831 |
| 3454 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractPmdReport extends AbstractMavenReport { /** * The output directory for the intermediate XML report. */ @Parameter( property = "project.build.directory", required = true ) protected File targetDirectory; /** * The output directory for the final HTML report. Note that this parameter is only evaluated if the goal is run * directly from the command line or during the default lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is used instead. */ @Parameter( property = "project.reporting.outputDirectory", required = true ) protected File outputDirectory; /** * Site rendering component for generating the HTML report. */ @Component private Renderer siteRenderer; /** * The project to analyse. */ @Parameter( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * Set the output format type, in addition to the HTML report. Must be one of: "none", "csv", "xml", "txt" or the * full class name of the PMD renderer to use. See the net.sourceforge.pmd.renderers package javadoc for available * renderers. XML is required if the pmd:check goal is being used. */ @Parameter( property = "format", defaultValue = "xml" ) protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is * being used. */ @Parameter( property = "linkXRef", defaultValue = "true" ) private boolean linkXRef; /** * Location of the Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref" ) private File xrefLocation; /** * Location of the Test Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) private File xrefTestLocation; /** * A list of files to exclude from checking. Can contain Ant-style wildcards and double wildcards. Note that these * exclusion patterns only operate on the path of a source file relative to its source root directory. In other * words, files are excluded based on their package and/or class name. If you want to exclude entire source root * directories, use the parameter excludeRoots instead. * * @since 2.2 */ @Parameter private List excludes; /** * A list of files to include from checking. Can contain Ant-style wildcards and double wildcards. Defaults to * **\/*.java. * * @since 2.2 */ @Parameter private List includes; /** * Specifies the location of the source directories to be used for PMD. * Defaults to project.compileSourceRoots. * @since 3.7 */ @Parameter( defaultValue = "${project.compileSourceRoots}" ) private List compileSourceRoots; /** * The directories containing the test-sources to be used for PMD. * Defaults to project.testCompileSourceRoots * @since 3.7 */ @Parameter( defaultValue = "${project.testCompileSourceRoots}" ) private List testSourceRoots; /** * The project source directories that should be excluded. * * @since 2.2 */ @Parameter private File[] excludeRoots; /** * Run PMD on the tests. * * @since 2.2 */ @Parameter( defaultValue = "false" ) protected boolean includeTests; /** * Whether to build an aggregated report at the root, or build individual reports. * * @since 2.2 */ @Parameter( property = "aggregate", defaultValue = "false" ) protected boolean aggregate; /** * The file encoding to use when reading the Java sources. * * @since 2.3 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String sourceEncoding; /** * The file encoding when writing non-HTML reports. * * @since 2.5 */ @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) private String outputEncoding; /** * The projects in the reactor for aggregation report. */ @Parameter( property = "reactorProjects", readonly = true ) protected List reactorProjects; /** * Whether to include the xml files generated by PMD/CPD in the site. * * @since 3.0 */ @Parameter( defaultValue = "false" ) protected boolean includeXmlInSite; /** * Skip the PMD/CPD report generation if there are no violations or duplications found. Defaults to * true. * * @since 3.1 */ @Parameter( defaultValue = "true" ) protected boolean skipEmptyReport; /** * File that lists classes and rules to be excluded from failures. * For PMD, this is a properties file. For CPD, this * is a text file that contains comma-separated lists of classes * that are allowed to duplicate. * * @since 3.7 */ @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) protected String excludeFromFailureFile; /** The files that are being analyzed. */ protected Map filesToProcess; /** * {@inheritDoc} */ @Override protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ @Override protected Renderer getSiteRenderer() { return siteRenderer; } protected String constructXRefLocation( boolean test ) { String location = null; if ( linkXRef ) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = PathTool.getRelativePath( outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath() ); if ( StringUtils.isEmpty( relativePath ) ) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); if ( xrefLoc.exists() ) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; } else { // Not yet generated - check if the report is on its way @SuppressWarnings( "unchecked" ) List reportPlugins = project.getReportPlugins(); for ( ReportPlugin plugin : reportPlugins ) { String artifactId = plugin.getArtifactId(); if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) { location = relativePath; } } } if ( location == null ) { getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); } } return location; } /** * Convenience method to get the list of files where the PMD tool will be executed * * @return a List of the files where the PMD tool will be executed * @throws IOException If an I/O error occurs during construction of the * canonical pathnames of the files */ protected Map getFilesToProcess() throws IOException { if ( aggregate && !project.isExecutionRoot() ) { return Collections.emptyMap(); } if ( excludeRoots == null ) { excludeRoots = new File[0]; } Collection excludeRootFiles = new HashSet<>( excludeRoots.length ); for ( File file : excludeRoots ) { if ( file.isDirectory() ) { excludeRootFiles.add( file ); } } List directories = new ArrayList<>(); if ( null == compileSourceRoots ) { compileSourceRoots = project.getCompileSourceRoots(); } if ( compileSourceRoots != null ) { for ( String root : compileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); } } } if ( null == testSourceRoots ) { testSourceRoots = project.getTestCompileSourceRoots(); } if ( includeTests ) { if ( testSourceRoots != null ) { for ( String root : testSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( project, sroot, testXref ) ); } } } } if ( aggregate ) { for ( MavenProject localProject : reactorProjects ) { @SuppressWarnings( "unchecked" ) List localCompileSourceRoots = localProject.getCompileSourceRoots(); for ( String root : localCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); } } if ( includeTests ) { @SuppressWarnings( "unchecked" ) List localTestCompileSourceRoots = localProject.getTestCompileSourceRoots(); for ( String root : localTestCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); } } } } } String excluding = getExcludes(); getLog().debug( "Exclusions: " + excluding ); String including = getIncludes(); getLog().debug( "Inclusions: " + including ); Map files = new TreeMap<>(); for ( PmdFileInfo finfo : directories ) { getLog().debug( "Searching for files in directory " + finfo.getSourceDirectory().toString() ); File sourceDirectory = finfo.getSourceDirectory(); if ( sourceDirectory.isDirectory() && !isDirectoryExcluded( excludeRootFiles, sourceDirectory ) ) { List newfiles = FileUtils.getFiles( sourceDirectory, including, excluding ); for ( File newfile : newfiles ) { files.put( newfile.getCanonicalFile(), finfo ); } } } return files; } private boolean isDirectoryExcluded( Collection excludeRootFiles, File sourceDirectoryToCheck ) { boolean returnVal = false; for ( File excludeDir : excludeRootFiles ) { try { if ( sourceDirectoryToCheck.getCanonicalPath().startsWith( excludeDir.getCanonicalPath() ) ) { getLog().debug( "Directory " + sourceDirectoryToCheck.getAbsolutePath() + " has been excluded as it matches excludeRoot " + excludeDir.getAbsolutePath() ); returnVal = true; break; } } catch ( IOException e ) { getLog().warn( "Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e ); } } return returnVal; } /** * Gets the comma separated list of effective include patterns. * * @return The comma separated list of effective include patterns, never null. */ private String getIncludes() { Collection patterns = new LinkedHashSet<>(); if ( includes != null ) { patterns.addAll( includes ); } if ( patterns.isEmpty() ) { patterns.add( "**/*.java" ); } return StringUtils.join( patterns.iterator(), "," ); } /** * Gets the comma separated list of effective exclude patterns. * * @return The comma separated list of effective exclude patterns, never null. */ private String getExcludes() { Collection patterns = new LinkedHashSet<>( FileUtils.getDefaultExcludesAsList() ); if ( excludes != null ) { patterns.addAll( excludes ); } return StringUtils.join( patterns.iterator(), "," ); } protected boolean isHtml() { return "html".equals( format ); } protected boolean isXml() { return "xml".equals( format ); } /** * {@inheritDoc} */ @Override public boolean canGenerateReport() { if ( aggregate && !project.isExecutionRoot() ) { return false; } if ( "pom".equals( project.getPackaging() ) && !aggregate ) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures if ( isXml() ) { return true; } try { filesToProcess = getFilesToProcess(); if ( filesToProcess.isEmpty() ) { return false; } } catch ( IOException e ) { getLog().error( e ); } return true; } /** * {@inheritDoc} */ @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } protected String getSourceEncoding() { return sourceEncoding; } /** * Gets the effective reporting output files encoding. * * @return The effective reporting output file encoding, never null. * @since 2.5 */ protected String getOutputEncoding() { return ( outputEncoding != null ) ? outputEncoding : ReaderFactory.UTF_8; } static String getPmdVersion() { try { return (String) PMD.class.getField( "VERSION" ).get( null ); } catch ( IllegalAccessException e ) { throw new RuntimeException( "PMD VERSION field not accessible", e ); } catch ( NoSuchFieldException e ) { throw new RuntimeException( "PMD VERSION field not found", e ); } } } |
data class | data class, long method | t | t | t | long method | 0 | 6936 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-pmd-plugin/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java/#L52-L553 | 1 | 3454 | 6936 | |
| 3479 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | long method, data class | t | t | t | data class | 0 | 7119 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 3479 | 7119 | |
| 3479 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7119 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 3479 | 7119 | ||
| 3506 | , all the code is well designed. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7525 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 2 | 3506 | 7525 | ||
| 3506 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7525 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 1 | 3506 | 7525 | ||
| 3521 | , I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/contentassist/antlr/internal/InternalN4JSParser.java/#L181223-L181248 | 2 | 3521 | 7615 | ||
| 3521 | { "input_code": "public class Example {\n private int a;\n private int b;\n \n public int calculateSum() {\n return a + b;\n }\n\n public void printValues() {\n System.out.println(\"Value a: \" + a);\n System.out.println(\"Value b: \" + b);\n }\n}", "detected_code_smells": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | yes i found bad smellsthe bad smells are:1. long method | t | t | t | 0 | 7615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/contentassist/antlr/internal/InternalN4JSParser.java/#L181223-L181248 | 1 | 3521 | 7615 | ||
| 3548 | { "input_code": "public class Example {\n private int x;\n private int y;\n\n public Example(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n public int calculateSum() {\n return x + y;\n }\n}", "detected_bad_smells": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | yes i found bad smells the bad smells are: 1. long method | t | t | t | 0 | 7729 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 3548 | 7729 | ||
| 3548 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7729 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 3548 | 7729 | ||
| 3557 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 7777 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 3557 | 7777 | ||
| 3573 | NO, I did not find any bad smells. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7856 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 3573 | 7856 | ||
| 3573 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7856 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 3573 | 7856 | ||
| 3581 | { "input": { "codeSmells": ["Blob", "Data Class", "Feature Envy", "Long Method"], "code": "public class MyClass {\n private int x;\n\n public void setX(int x) {\n this.x = x;\n }\n\n public int getX() {\n return x;\n }\n}" }, "output": { "message": "YES I found bad smells", "detectedCodeSmells": "the bad smells are: 3. Data Class" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | message: yes i found bad smells, detectedcodesmells: the bad smells are: 3. data class | t | t | f | message: yes i found bad smells, detectedcodesmells: the bad smells are: 3. data class | feature envy | 0 | 7900 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/service/cpi/SharingRegistryService.java/#L41810-L41827 | 1 | 3581 | 7900 |
| 3581 | of the below code has smelly codes No bad smells found. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 7900 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/service/cpi/SharingRegistryService.java/#L41810-L41827 | 2 | 3581 | 7900 | ||
| 3587 | { "message": "Please provide the Java code for analysis." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | Not specified | f | f | f | false | 0 | 7921 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 3587 | 7921 | |
| 3587 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7921 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 3587 | 7921 | ||
| 3588 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 7922 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 3588 | 7922 | ||
| 3588 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 7922 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 3588 | 7922 | ||
| 3589 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | long method, data class | t | t | t | data class | 0 | 7923 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 1 | 3589 | 7923 | |
| 3589 | the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | Long method2 Feature envy | f | f | t | 0 | 7923 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 2 | 3589 | 7923 | ||
| 3621 | of the detected smells are omitted in the answer YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8146 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 2 | 3621 | 8146 | ||
| 3621 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 8146 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 1 | 3621 | 8146 | ||
| 3634 | { "message": "YES I found bad smells", "detected_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ImmediatelyThrowsEvent makeImmediatelyThrowsEvent(final int processId, final int invokeId, final Throwable throwable) { if (null == immediatelyThrowsEvent) { immediatelyThrowsEvent = new ImmediatelyThrowsEvent(ILLEGAL_PROCESS_ID, ILLEGAL_INVOKE_ID, null); } unsafe.putInt(immediatelyThrowsEvent, processIdFieldInInvokeEventOffset, processId); unsafe.putInt(immediatelyThrowsEvent, invokeIdFieldInInvokeEventOffset, invokeId); unsafe.putObject(immediatelyThrowsEvent, throwableFieldInThrowsEventOffset, throwable); return immediatelyThrowsEvent; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8213 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/enhance/weaver/SingleEventFactory.java/#L130-L140 | 1 | 3634 | 8213 |
| 3634 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number usage (values such as ILLEGAL_PROCESS_ID and ILLEGAL_INVOKE_ID are not easily understandable without context) 3. Feature envy (the method is accessing multiple fields from the immediatelyThrowsEvent object, indicating that the logic might be better placed inside the object itself) 4. Possible duplicate code (the immediatelyThrowsEvent object is always initialized with the same values, so the if statement could potentially be removed) 5. Insufficient error handling (the method doesn't perform any checks to ensure that the provided parameters are valid and could throw an exception) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ImmediatelyThrowsEvent makeImmediatelyThrowsEvent(final int processId, final int invokeId, final Throwable throwable) { if (null == immediatelyThrowsEvent) { immediatelyThrowsEvent = new ImmediatelyThrowsEvent(ILLEGAL_PROCESS_ID, ILLEGAL_INVOKE_ID, null); } unsafe.putInt(immediatelyThrowsEvent, processIdFieldInInvokeEventOffset, processId); unsafe.putInt(immediatelyThrowsEvent, invokeIdFieldInInvokeEventOffset, invokeId); unsafe.putObject(immediatelyThrowsEvent, throwableFieldInThrowsEventOffset, throwable); return immediatelyThrowsEvent; } |
feature envy | Long method2 Magic number usage (values such as ILLEGAL_PROCESS_ID and ILLEGAL_INVOKE_ID are not easily understandable without context)3 Feature envy (the method is accessing multiple fields from the immediatelyThrowsEvent object, indicating that the logic might be better placed inside the object itself)4 Possible duplicate code (the immediatelyThrowsEvent object is always initialized with the same values, so the if statement could potentially be removed)5 Insufficient error handling (the method doesn't perform any checks to ensure that the provided parameters are valid and could throw an exception) | t | f | t | indicating that the logic might be better placed inside the object itself)4. Possible duplicate code (the immediatelyThrowsEvent object is always initialized with the same values, so the if statement could potentially be removed)5. Insufficient error handling (the method doesn't perform any checks to ensure that the provided parameters are valid and could throw an exception) | 0 | 8213 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/enhance/weaver/SingleEventFactory.java/#L130-L140 | 2 | 3634 | 8213 | |
| 3638 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 8239 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xtext.ui.examples/projects/domainmodel/org.eclipse.xtext.example.domainmodel.ide/src-gen/org/eclipse/xtext/example/domainmodel/ide/contentassist/antlr/internal/InternalDomainmodelParser.java/#L62002-L62027 | 1 | 3638 | 8239 | ||
| 3653 | { protected int[][] values; protected int maxValue; public ArrayImageSource( int width, int height, int[][] values ) { super( width, height ); this.values = values; public int getRGB( int x, int y ) { return values[x][y]; } YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8313 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 3653 | 8313 |
| 3653 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | long method, data class | t | t | t | long method | 0 | 8313 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 3653 | 8313 | |
| 3663 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnnotationSubstitutionType extends CustomSubstitutionType { private final String name; public AnnotationSubstitutionType(MetaAccessProvider metaAccess, ResolvedJavaType original) { super(original); assert original.getSuperclass().equals(metaAccess.lookupJavaType(Proxy.class)); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(original); ResolvedJavaType annotationInterfaceType = AnnotationSupport.findAnnotationInterfaceType(original); assert annotationInterfaceType.isAssignableFrom(original); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(annotationInterfaceType); String n = annotationInterfaceType.getName(); assert n.endsWith(";"); name = n.substring(0, n.length() - 1) + "$$ProxyImpl;"; } @Override public String getName() { return name; } @Override public String toString() { return "AnnotationType<" + toJavaName(true) + " -> " + original + ">"; } } |
data class | data class | t | t | t | 0 | 8426 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/annotation/AnnotationSubstitutionType.java/#L33-L61 | 1 | 3663 | 8426 | ||
| 3663 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnnotationSubstitutionType extends CustomSubstitutionType { private final String name; public AnnotationSubstitutionType(MetaAccessProvider metaAccess, ResolvedJavaType original) { super(original); assert original.getSuperclass().equals(metaAccess.lookupJavaType(Proxy.class)); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(original); ResolvedJavaType annotationInterfaceType = AnnotationSupport.findAnnotationInterfaceType(original); assert annotationInterfaceType.isAssignableFrom(original); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(annotationInterfaceType); String n = annotationInterfaceType.getName(); assert n.endsWith(";"); name = n.substring(0, n.length() - 1) + "$$ProxyImpl;"; } @Override public String getName() { return name; } @Override public String toString() { return "AnnotationType<" + toJavaName(true) + " -> " + original + ">"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8426 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/annotation/AnnotationSubstitutionType.java/#L33-L61 | 2 | 3663 | 8426 |
| 3676 | { "response": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public WeightedAshwoodEntitySorter() { this.weightedDbEntityComparator = new WeightedDbEntityComparator(); this.weightedObjEntityComparator = new WeightedObjEntityComparator(); this.entityWeights = Collections.emptyMap(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 8524 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/ashwood/WeightedAshwoodEntitySorter.java/#L42-L46 | 1 | 3676 | 8524 |
| 3676 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public WeightedAshwoodEntitySorter() { this.weightedDbEntityComparator = new WeightedDbEntityComparator(); this.weightedObjEntityComparator = new WeightedObjEntityComparator(); this.entityWeights = Collections.emptyMap(); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 8524 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/ashwood/WeightedAshwoodEntitySorter.java/#L42-L46 | 2 | 3676 | 8524 | |
| 3694 | { "output": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | 1. long method | t | t | t | 0 | 8659 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 3694 | 8659 | ||
| 3694 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8659 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 3694 | 8659 | ||
| 3707 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 8853 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 1 | 3707 | 8853 | |
| 3707 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Magic number, 4.Throws declaration, 5.Overutilization of try-catch blocks, 6.Duplicate code, 7.Potentially unnecessary variable assignment, 8.Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | Long method, 2Feature envy, 3Magic number, 4Throws declaration, 5Overutilization of try-catch blocks, 6Duplicate code, 7Potentially unnecessary variable assignment, 8Inconsistent naming conventions | t | f | t | 2.Feature envy, 3.Magic number, 4.Throws declaration, 5.Overutilization of try-catch blocks, 6.Duplicate code, 7.Potentially unnecessary variable assignment, 8.Inconsistent naming conventions. | 0 | 8853 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 2 | 3707 | 8853 | |
| 3714 | YES, I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExistingEnumElements extends AbstractEnumRuleElementFinder { private final EnumRule rule = (EnumRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.enumrules.EnumRulesTestLanguage.ExistingEnum"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final EnumLiteralDeclaration cSameNameEnumLiteralDeclaration_0 = (EnumLiteralDeclaration)cAlternatives.eContents().get(0); private final Keyword cSameNameSameNameKeyword_0_0 = (Keyword)cSameNameEnumLiteralDeclaration_0.eContents().get(0); private final EnumLiteralDeclaration cOverriddenLiteralEnumLiteralDeclaration_1 = (EnumLiteralDeclaration)cAlternatives.eContents().get(1); private final Keyword cOverriddenLiteralOverriddenKeyword_1_0 = (Keyword)cOverriddenLiteralEnumLiteralDeclaration_1.eContents().get(0); private final EnumLiteralDeclaration cDifferentNameEnumLiteralDeclaration_2 = (EnumLiteralDeclaration)cAlternatives.eContents().get(2); private final Keyword cDifferentNameDifferentLiteralKeyword_2_0 = (Keyword)cDifferentNameEnumLiteralDeclaration_2.eContents().get(0); //enum ExistingEnum: // SameName | OverriddenLiteral="overridden" | DifferentName="DifferentLiteral"; public EnumRule getRule() { return rule; } //SameName | OverriddenLiteral="overridden" | DifferentName="DifferentLiteral" public Alternatives getAlternatives() { return cAlternatives; } //SameName public EnumLiteralDeclaration getSameNameEnumLiteralDeclaration_0() { return cSameNameEnumLiteralDeclaration_0; } //"SameName" public Keyword getSameNameSameNameKeyword_0_0() { return cSameNameSameNameKeyword_0_0; } //OverriddenLiteral="overridden" public EnumLiteralDeclaration getOverriddenLiteralEnumLiteralDeclaration_1() { return cOverriddenLiteralEnumLiteralDeclaration_1; } //"overridden" public Keyword getOverriddenLiteralOverriddenKeyword_1_0() { return cOverriddenLiteralOverriddenKeyword_1_0; } //DifferentName="DifferentLiteral" public EnumLiteralDeclaration getDifferentNameEnumLiteralDeclaration_2() { return cDifferentNameEnumLiteralDeclaration_2; } //"DifferentLiteral" public Keyword getDifferentNameDifferentLiteralKeyword_2_0() { return cDifferentNameDifferentLiteralKeyword_2_0; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 8980 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.extras.tests/src-gen/org/eclipse/xtext/enumrules/services/EnumRulesTestLanguageGrammarAccess.java/#L88-L122 | 2 | 3714 | 8980 |
| 3750 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, PhoenixIndexFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 9355 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/write/IndexWriter.java/#L87-L100 | 1 | 3750 | 9355 |
| 3750 | YES I found bad smells The bad smells are: 1. Long method 2. Exception handling within the method instead of delegating it to another class or method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, PhoenixIndexFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } |
feature envy | Long method2 Exception handling within the method instead of delegating it to another class or method | t | f | f | . Long method2. Exception handling within the method instead of delegating it to another class or method. | feature envy | 0 | 9355 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/write/IndexWriter.java/#L87-L100 | 2 | 3750 | 9355 |
| 3763 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CurrentCreationalContext { private final ThreadLocal> creationalContext = new ThreadLocal>(); public CreationalContext get() { return creationalContext.get(); } public void set(CreationalContext value) { creationalContext.set(value); } public void remove() { creationalContext.remove(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 9405 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/cdi/CurrentCreationalContext.java/#L24-L38 | 2 | 3763 | 9405 |
| 3766 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void generateReport( Locale locale, LinkcheckModel linkcheckModel ) { LinkcheckReportGenerator reportGenerator = new LinkcheckReportGenerator( i18n ); reportGenerator.setExcludedHttpStatusErrors( excludedHttpStatusErrors ); reportGenerator.setExcludedHttpStatusWarnings( excludedHttpStatusWarnings ); reportGenerator.setExcludedLinks( excludedLinks ); reportGenerator.setExcludedPages( excludedPages ); reportGenerator.setHttpFollowRedirect( httpFollowRedirect ); reportGenerator.setHttpMethod( httpMethod ); reportGenerator.setOffline( offline ); reportGenerator.generateReport( locale, linkcheckModel, getSink() ); closeReport(); // Copy the images copyStaticResources(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9426 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-linkcheck-plugin/src/main/java/org/apache/maven/plugins/linkcheck/LinkcheckReport.java/#L448-L465 | 1 | 3766 | 9426 |
| 3766 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void generateReport( Locale locale, LinkcheckModel linkcheckModel ) { LinkcheckReportGenerator reportGenerator = new LinkcheckReportGenerator( i18n ); reportGenerator.setExcludedHttpStatusErrors( excludedHttpStatusErrors ); reportGenerator.setExcludedHttpStatusWarnings( excludedHttpStatusWarnings ); reportGenerator.setExcludedLinks( excludedLinks ); reportGenerator.setExcludedPages( excludedPages ); reportGenerator.setHttpFollowRedirect( httpFollowRedirect ); reportGenerator.setHttpMethod( httpMethod ); reportGenerator.setOffline( offline ); reportGenerator.generateReport( locale, linkcheckModel, getSink() ); closeReport(); // Copy the images copyStaticResources(); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9426 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-linkcheck-plugin/src/main/java/org/apache/maven/plugins/linkcheck/LinkcheckReport.java/#L448-L465 | 2 | 3766 | 9426 |
| 3786 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | long method | t | t | t | 0 | 9536 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 3786 | 9536 | ||
| 3786 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Excessive conditional complexity 4. Code duplication 5. Poorly named variables ("this_present_protocol_version" and "that_present_protocol_version") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy3 Excessive conditional complexity4 Code duplication5 Poorly named variables ("this_present_protocol_version" and "that_present_protocol_version") | t | f | t | 0 | 9536 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 3786 | 9536 | ||
| 3787 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 9539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 3787 | 9539 |
| 3787 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 9539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 2 | 3787 | 9539 |
| 3794 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Not specified | f | f | f | false | 0 | 9585 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 1 | 3794 | 9585 | |
| 3794 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 9585 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 2 | 3794 | 9585 | |
| 3795 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | 1. long method | t | t | t | 0 | 9593 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 3795 | 9593 | ||
| 3795 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9593 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 3795 | 9593 | ||
| 3797 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 9604 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 1 | 3797 | 9604 | |
| 3797 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | Long method2 Feature envy | t | f | t | 0 | 9604 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 2 | 3797 | 9604 | ||
| 3801 | { "input_code": "public class Calculator { public int add(int num1, int num2) { int sum = num1 + num2; return sum; } public int multiply(int num1, int num2) { int product = num1 * num2; return product; }}", "code_smells_to_check": ["Blob", "Data Class", "Feature Envy", "Long Method"], "identified_bad_smells": { "detected": false } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | detected: false | t | t | f | detected: false | feature envy | 0 | 9635 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1280-L1292 | 1 | 3801 | 9635 |
| 3801 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9635 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1280-L1292 | 2 | 3801 | 9635 | ||
| 3803 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 9644 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 3803 | 9644 |
| 3803 | "}; YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions 4. Use of raw types without generics 5. Unnecessary comments 6. Poor error handling 7. Unnecessary complexity 8. Magic numbers without meaningful names 9. Code redundancy 10. Dependency on hardcoded values 11. Inefficient use of data structures 12. Lack of proper error/exception handling 13. Mixing of different responsibilities in one method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
feature envy | Long method2 Feature envy 3 Inconsistent naming conventions 4 Use of raw types without generics 5 Unnecessary comments 6 Poor error handling 7 Unnecessary complexity 8 Magic numbers without meaningful names 9 Code redundancy | t | f | t | 0 | 9644 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 3803 | 9644 | ||
| 3806 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | long method | t | t | t | 0 | 9657 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 3806 | 9657 | ||
| 3806 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Shotgun surgery 5. Duplicate code 6. Inconsistent formatting 7. Poor naming conventions 8. Magic numbers 9. Hard-coded values 10. Excessive commenting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy3 Data class4 Shotgun surgery5 Duplicate code6 Inconsistent formatting7 Poor naming conventions8 Magic numbers9 Hard-coded values | t | f | t | 0 | 9657 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 3806 | 9657 | ||
| 3811 | { "input_code": "public class Product {\n private String name;\n private double price;\n public Product(String name, double price) {\n this.name = name;\n this.price = price;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public double calculateTax() {\n return price * 0.1;\n }\n}", "code_smells_to_check": ["Blob", "Data Class", "Feature Envy", "Long Method"], "detected_code_smells": [] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | t | t | f | feature envy | 0 | 9700 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 1 | 3811 | 9700 | ||
| 3811 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9700 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 2 | 3811 | 9700 | ||
| 3812 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 9703 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 1 | 3812 | 9703 | ||
| 3812 | of the smells are contained as the code is well written. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 9703 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 2 | 3812 | 9703 | ||
| 3814 | {"error": "Sorry, I cannot provide code analysis or detect code smells. However, I can offer guidance or information on how to identify and address common code smells in Java code."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ClasspathUriUtil { public static final String CLASSPATH_SCHEME = "classpath"; public static boolean isClasspathUri(URI uri) { if (uri == null) return false; String scheme = uri.scheme(); return CLASSPATH_SCHEME.equals(scheme); } } |
data class | f | f | f | data class | 0 | 9713 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/resource/ClasspathUriUtil.java/#L20-L31 | 1 | 3814 | 9713 | ||
| 3814 | YES I found bad smells the bad smells are: 1.Magic number, 2.Inconsistent naming Convention, 3.Inconsistent formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ClasspathUriUtil { public static final String CLASSPATH_SCHEME = "classpath"; public static boolean isClasspathUri(URI uri) { if (uri == null) return false; String scheme = uri.scheme(); return CLASSPATH_SCHEME.equals(scheme); } } |
data class | Magic number, 2Inconsistent naming Convention, 3Inconsistent formatting | t | f | f | .Magic number, 2.Inconsistent naming Convention, 3.Inconsistent formatting | data class | 0 | 9713 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/resource/ClasspathUriUtil.java/#L20-L31 | 2 | 3814 | 9713 |
| 3818 | { "output": "YES I found bad smells the bad smells are: 3. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | 3. long method | t | t | f | 3. long method | data class | 0 | 9732 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 1 | 3818 | 9732 |
| 3818 | YES, I found bad smells. The bad smells are: 1. Long method 2. Data class 3. Data clumps 4. Feature envy 5. Primitive obsession 6. Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | Long method2 Data class3 Data clumps4 Feature envy5 Primitive obsession6 Message chains | t | f | t | 0 | 9732 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 2 | 3818 | 9732 | ||
| 3834 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9880 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 3834 | 9880 |
| 3834 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9880 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 3834 | 9880 | ||
| 3840 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | long method | t | t | t | 0 | 9895 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 3840 | 9895 | ||
| 3840 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9895 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 3840 | 9895 | ||
| 3842 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void transition(JobImpl job, JobEvent event) { job.addDiagnostic(((JobDiagnosticsUpdateEvent) event) .getDiagnosticUpdate()); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9936 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java/#L2115-L2119 | 1 | 3842 | 9936 |
| 3842 | YES I found bad smells. 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void transition(JobImpl job, JobEvent event) { job.addDiagnostic(((JobDiagnosticsUpdateEvent) event) .getDiagnosticUpdate()); } |
feature envy | Feature envy | t | f | t | 0 | 9936 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java/#L2115-L2119 | 2 | 3842 | 9936 | ||
| 3849 | {"message": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int year = gc.cdate.getNormalizedYear(); if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) { long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate)); BaseCalendar.Date d = getCalendarDate(month1); return d.getDayOfMonth(); } } return getMinimum(field); } /** * Returns the maximum value that this calendar field could have, * taking into consideration the given time value and the current |
feature envy | f | f | f | feature envy | 0 | 9990 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/GregorianCalendar.java/#L1674-L1686 | 1 | 3849 | 9990 | ||
| 3849 | * values of the calendar fields. * YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method 3. Feature envy 4. Inconsistent variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int year = gc.cdate.getNormalizedYear(); if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) { long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate)); BaseCalendar.Date d = getCalendarDate(month1); return d.getDayOfMonth(); } } return getMinimum(field); } /** * Returns the maximum value that this calendar field could have, * taking into consideration the given time value and the current |
feature envy | Magic numbers2 Long method3 Feature envy4 Inconsistent variable naming | t | f | t | 0 | 9990 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/GregorianCalendar.java/#L1674-L1686 | 2 | 3849 | 9990 | ||
| 3854 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | data class | t | t | t | 0 | 10010 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 3854 | 10010 | ||
| 3854 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10010 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 3854 | 10010 |
| 3855 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class MouseObservationEvent extends ObservationEvent { private int deltaX; private int deltaY; private int deltaZ; public MouseObservationEvent(int deltaX, int deltaY, int deltaZ) { super(); this.deltaX = deltaX; this.deltaY = deltaY; this.deltaZ = deltaZ; } @Override public JsonObject getJSON() { JsonObject jsonEvent = new JsonObject(); jsonEvent.addProperty("time", this.timestamp); jsonEvent.addProperty("type", "mouse"); jsonEvent.addProperty("deltaX", this.deltaX); jsonEvent.addProperty("deltaY", this.deltaY); jsonEvent.addProperty("deltaZ", this.deltaZ); return jsonEvent; } } |
data class | long method, data class | t | t | t | long method | 0 | 10011 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/ObservationFromHumanImplementation.java/#L29-L54 | 1 | 3855 | 10011 | |
| 3855 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class MouseObservationEvent extends ObservationEvent { private int deltaX; private int deltaY; private int deltaZ; public MouseObservationEvent(int deltaX, int deltaY, int deltaZ) { super(); this.deltaX = deltaX; this.deltaY = deltaY; this.deltaZ = deltaZ; } @Override public JsonObject getJSON() { JsonObject jsonEvent = new JsonObject(); jsonEvent.addProperty("time", this.timestamp); jsonEvent.addProperty("type", "mouse"); jsonEvent.addProperty("deltaX", this.deltaX); jsonEvent.addProperty("deltaY", this.deltaY); jsonEvent.addProperty("deltaZ", this.deltaZ); return jsonEvent; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 10011 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/ObservationFromHumanImplementation.java/#L29-L54 | 2 | 3855 | 10011 |
| 3862 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | data class | t | t | t | 0 | 10055 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 3862 | 10055 | ||
| 3862 | YES I found bad smells. Bad smells are: 1. Long methods - the class contains a lot of getters, setters, and methods with similar functionality. 2. Feature envy - the class is more concerned with manipulating data rather than performing specific actions or behaviors related to a specific shape entity, indicating data and behavior should be better encapsulated within a Shape class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | Long methods - the class contains a lot of getters, setters, and methods with similar functionality2 Feature envy - the class is more concerned with manipulating data rather than performing specific actions or behaviors related to a specific shape entity, indicating data and behavior should be better encapsulated within a Shape class | t | f | f | . Long methods - the class contains a lot of getters, setters, and methods with similar functionality.2. Feature envy - the class is more concerned with manipulating data rather than performing specific actions or behaviors related to a specific shape entity, indicating data and behavior should be better encapsulated within a Shape class. | data class | 0 | 10055 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 3862 | 10055 |
| 3875 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | 1. data class | t | t | t | 0 | 10123 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 1 | 3875 | 10123 | ||
| 3875 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10123 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 2 | 3875 | 10123 |
| 3876 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10126 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 3876 | 10126 |
| 3876 | YES I found bad smells The bad smells are: 1.Null check, 2.Long method, 3.Magic number, 4.Incomplete conditional logic, 5.Misleading comment | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | Null check, 2Long method, 3Magic number, 4Incomplete conditional logic, 5Misleading comment | t | f | f | .Null check, 2.Long method, 3.Magic number, 4.Incomplete conditional logic, 5.Misleading comment | feature envy | 0 | 10126 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 3876 | 10126 |
| 3889 | { "message": "YES I found bad smells", "bad_smells": [ {"1": "Long Method"} ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 10168 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 1 | 3889 | 10168 |
| 3889 | YES, I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 10168 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 2 | 3889 | 10168 | |
| 3902 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | long method | t | t | t | 0 | 10217 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 1 | 3902 | 10217 | ||
| 3902 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | Long method | t | f | t | 0 | 10217 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 2 | 3902 | 10217 | ||
| 3903 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | 1. long method | t | t | t | 0 | 10219 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 3903 | 10219 | ||
| 3903 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10219 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 3903 | 10219 | ||
| 3905 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | 1. long method | t | t | t | 0 | 10223 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 3905 | 10223 | ||
| 3905 | the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method, 2 Feature envy | f | f | t | 2. Feature envy | 0 | 10223 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 3905 | 10223 | |
| 3909 | { "message": "YES I found bad smells", "bad smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | 1. data class | t | t | t | 0 | 10235 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 1 | 3909 | 10235 | ||
| 3909 | YES, I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10235 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 2 | 3909 | 10235 |
| 3912 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method | t | t | t | 0 | 10243 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 3912 | 10243 | ||
| 3912 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10243 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 3912 | 10243 | ||
| 3913 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10244 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 3913 | 10244 |
| 3913 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10244 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 3913 | 10244 | ||
| 3920 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | data class, long method | t | t | t | long method | 0 | 10262 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 1 | 3920 | 10262 | |
| 3920 | YES I found bad smells the bad smells are: 1.Short class, 2.Empty catch clause, 3. Meaningless class name, 4. Inappropriate inheritance, 5. Feature envy, 6. Inappropriate method name | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | Short class,2Empty catch clause, 3 Meaningless class name, 4 Inappropriate inheritance,5 Feature envy, 6 Inappropriate method name | t | f | f | .Short class, 2.Empty catch clause, 3. Meaningless class name, 4. Inappropriate inheritance, 5. Feature envy, 6. Inappropriate method name | data class | 0 | 10262 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 2 | 3920 | 10262 |
| 3923 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10270 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 3923 | 10270 |
| 3923 | YES, I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 10270 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 3923 | 10270 |
| 3925 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 10274 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 1 | 3925 | 10274 |
| 3925 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Inappropriate intimacy 5. Message chain 6. Duplicated code 7. Magic numbers 8. Data class 9. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long method 2 Feature envy 3 Primitive obsession 4 Inappropriate intimacy 5 Message chain 6 Duplicated code 7 Magic numbers 8 Data class 9 Lazy class | t | f | t | 0 | 10274 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 3925 | 10274 | ||
| 3933 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10289 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 3933 | 10289 |
| 3933 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10289 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 3933 | 10289 | |
| 3937 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method | t | t | t | 0 | 10309 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 3937 | 10309 | ||
| 3937 | YES I found bad smells The bad smells are: 1.Long method, 2.Magic number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method, 2Magic number | t | f | t | 2.Magic number | 0 | 10309 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 3937 | 10309 | |
| 3940 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10313 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 3940 | 10313 | ||
| 3940 | YES I found bad smells the bad smells are: 1. Long Method 2. Duplicate Code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long Method2 Duplicate Code3 Feature Envy | t | f | t | 0 | 10313 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 3940 | 10313 | ||
| 3947 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10329 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 3947 | 10329 |
| 3960 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | long method, data class | t | t | t | long method | 0 | 10368 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 3960 | 10368 | |
| 3960 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10368 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 3960 | 10368 |
| 3962 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | data class | t | t | t | 0 | 10380 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 3962 | 10380 | ||
| 3964 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | long method | t | t | t | 0 | 10391 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 3964 | 10391 | ||
| 3964 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent formatting 5. Lack of comments/documentation 6. Poor variable naming 7. Potential for NullPointerException 8. Inefficient use of if/else blocks 9. Code repetition 10. Inappropriate use of nested loops 11. Poor exception handling 12. Potential for logical errors 13. Inconsistent use of braces 14. Lack of abstraction 15. Poor separation of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Feature envy3 Duplicated code4 Inconsistent formatting5 Lack of comments/documentation6 Poor variable naming7 Potential for NullPointerException8 Inefficient use of if/else blocks9 Code repetition | t | f | t | 0 | 10391 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 3964 | 10391 | ||
| 3966 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 10400 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 1 | 3966 | 10400 | ||
| 3966 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 10400 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 2 | 3966 | 10400 | ||
| 3968 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10409 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 3968 | 10409 | ||
| 3975 | YES I found bad smells The bad smells are: 1. Feature envy, 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Feature envy, 2 Long method | t | f | f | . Feature envy, 2. Long method | data class | 0 | 10430 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 3975 | 10430 |
| 3986 | Please start your answer with"YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". YES I found bad smells: 1. Long method, 2. Repeated code, 3. Catch-all exception, 4. Unclear/inefficient variable names, 5. Possible feature envy with the repeated calls to oDataJPAContext.getODataJPATransaction(), 6. Possible violation of Single Responsibility Principle with the multiple functions being performed by the method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | Long method, 2 Repeated code, 3 Catch-all exception, 4 Unclear/inefficient variable names, 5 Possible feature envy with the repeated calls to oDataJPAContextgetODataJPATransaction(), 6 Possible violation of Single Responsibility Principle with the multiple functions being performed by the method | t | f | t | . Long method, 2. Repeated code, 3. Catch-all exception, 4. Unclear/inefficient variable names, 6. Possible violation of Single Responsibility Principle with the multiple functions being performed by the method. | 0 | 10501 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 3986 | 10501 | |
| 3987 | YES I found bad smells the bad smells are: 1. Long method 2. Unnecessary use of try-catch-finally block for exception handling 3. Use of generic exceptions instead of specific ones 4. Lack of modularization or abstraction in the code 5. Use of primitive data types instead of classes for handling requests and responses 6. Inconsistent use of method parameters (e.g. handler vs. requests) 7. Mixing of different responsibilities within the method (e.g. transaction handling, error handling, request processing) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
long method | Long method2 Unnecessary use of try-catch-finally block for exception handling3 Use of generic exceptions instead of specific ones4 Lack of modularization or abstraction in the code5 Use of primitive data types instead of classes for handling requests and responses6 Inconsistent use of method parameters (eg handler vs requests)7 Mixing of different responsibilities within the method (eg transaction handling, error handling, request processing) | t | f | t | error handling, request processing) | 0 | 10502 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 3987 | 10502 | |
| 3994 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | 1. data class | t | t | t | 0 | 10543 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 1 | 3994 | 10543 | ||
| 3994 | YES I found bad smells. the bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | data class | 0 | 10543 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 2 | 3994 | 10543 |
| 3999 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | data class | t | t | t | 0 | 10569 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 3999 | 10569 | ||
| 3999 | YES I found bad smells the bad smells are: 1. Long method (the class has only one method, but it could still be considered a long method as it performs multiple tasks). 2. Feature envy (the class is accessing a lot of data from other classes instead of handling it within itself). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method (the class has only one method, but it could still be considered a long method as it performs multiple tasks)2 Feature envy (the class is accessing a lot of data from other classes instead of handling it within itself) | t | f | f | . Long method (the class has only one method, but it could still be considered a long method as it performs multiple tasks).2. Feature envy (the class is accessing a lot of data from other classes instead of handling it within itself). | data class | 0 | 10569 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 3999 | 10569 |
| 4001 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10574 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 4001 | 10574 | ||
| 4008 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10594 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 4008 | 10594 |
| 4008 | YES I found bad smells The bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | Long method2Feature envy | t | f | t | 0 | 10594 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 4008 | 10594 | ||
| 4011 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10604 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 4011 | 10604 | |
| 4011 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10604 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 4011 | 10604 | ||
| 4023 | { "response": "YES, I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | long method, data class | t | t | t | long method | 0 | 10632 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 1 | 4023 | 10632 | |
| 4023 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10632 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 2 | 4023 | 10632 |
| 4024 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10635 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 1 | 4024 | 10635 | |
| 4024 | YES, I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | Feature envy | t | f | t | 0 | 10635 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 2 | 4024 | 10635 | ||
| 4031 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy 2 Long method | t | f | f | . Feature envy 2. Long method | data class | 0 | 10668 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 2 | 4031 | 10668 |
| 4034 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
feature envy | the bad smells are: long method, data class | t | t | f | the bad smells are: long method, data class | feature envy | 0 | 10674 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 4034 | 10674 |
| 4034 | Yes I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10674 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 4034 | 10674 | ||
| 4040 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10682 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 4040 | 10682 |
| 4040 | YES I found bad smells.the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10682 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 4040 | 10682 | ||
| 4044 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method, data class | t | t | t | data class | 0 | 10690 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 4044 | 10690 | |
| 4044 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10690 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 4044 | 10690 | ||
| 4048 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | long method | t | t | t | 0 | 10697 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 4048 | 10697 | ||
| 4048 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Primitive obsession 4. Data class 5. Message chains 6. Feature envy 7. Inappropriate intimacy (calling methods from parent class) 8. Mixed levels of abstraction 9. Code repetition (multiple use of "dis" variable) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long method2 Long parameter list3 Primitive obsession4 Data class5 Message chains6 Feature envy7 Inappropriate intimacy (calling methods from parent class)8 Mixed levels of abstraction9 Code repetition (multiple use of "dis" variable) | t | f | t | 0 | 10697 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 4048 | 10697 | ||
| 4051 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10700 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 4051 | 10700 |
| 4051 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10700 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 4051 | 10700 | ||
| 4052 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10701 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 4052 | 10701 | |
| 4052 | YES I found bad smells the bad smells are: 1. Long method 2. Commented out code 3. Complex conditional logic 4. Project-specific variable names 5. Unused variables 6. Multiple responsibilities 7. Debug logging statements 8. Side effects within method 9. Lack of abstraction/modularity 10. Magic numbers/constants 11. Inadequate comments/documentation 12. Excessive use of types and casting 13. Mutable state 14. Hard-coded values 15. Unused imports | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
feature envy | Long method2 Commented out code3 Complex conditional logic 4 Project-specific variable names 5 Unused variables6 Multiple responsibilities 7 Debug logging statements8 Side effects within method9 Lack of abstraction/modularity | t | f | f | . Long method2. Commented out code3. Complex conditional logic 4. Project-specific variable names 5. Unused variables6. Multiple responsibilities 7. Debug logging statements8. Side effects within method9. Lack of abstraction/modularity | feature envy | 0 | 10701 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 4052 | 10701 |
| 4065 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | long method | t | t | t | 0 | 10729 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 4065 | 10729 | ||
| 4065 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Multiple return points 4. Excessive comments 5. Nested loops or conditionals 6. Inconsistent formatting and coding style 7. Magic numbers or hardcoded values 8. Violation of the Single Responsibility Principle 9. Complex and unreadable code 10. Lack of documentation or proper naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | Long method2 Feature envy3 Multiple return points4 Excessive comments5 Nested loops or conditionals6 Inconsistent formatting and coding style7 Magic numbers or hardcoded values8 Violation of the Single Responsibility Principle9 Complex and unreadable code | t | f | t | 0 | 10729 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 4065 | 10729 | ||
| 4074 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10748 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 4074 | 10748 |
| 4074 | YES I found bad smells the bad smells are: 1. Long method, 2. Inconsistent naming (e.g. testST and sequenceType), 3. Coupled logic (each if statement depends on the previous one), 4. Opaque and confusing logic (e.g. the variable vType), 5. Duplicate code (check for AtomicType and NodeType is similar), 6. Inefficient use of inheritance (using instanceof instead of polymorphism), 7. Inconsistent formatting (indentation is inconsistent), 8. Over-complicated logic (multiple nested if statements), 9. Magic numbers (e.g. NodeKind constants), 10. No comments or documentation to explain the purpose of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
feature envy | Long method, 2 Inconsistent naming (eg testST and sequenceType), 3 Coupled logic (each if statement depends on the previous one), 4 Opaque and confusing logic (eg the variable vType), 5 Duplicate code (check for AtomicType and NodeType is similar), 6 Inefficient use of inheritance (using instanceof instead of polymorphism), 7 Inconsistent formatting (indentation is inconsistent), 8 Over-complicated logic (multiple nested if statements), 9 Magic numbers (eg NodeKind constants), | t | f | f | . Long method, 2. Inconsistent naming (e.g. testST and sequenceType), 3. Coupled logic (each if statement depends on the previous one), 4. Opaque and confusing logic (e.g. the variable vType), 5. Duplicate code (check for AtomicType and NodeType is similar), 6. Inefficient use of inheritance (using instanceof instead of polymorphism), 7. Inconsistent formatting (indentation is inconsistent), 8. Over-complicated logic (multiple nested if statements), 9. Magic numbers (e.g. NodeKind constants), | feature envy | 0 | 10748 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 4074 | 10748 |
| 4081 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10762 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 4081 | 10762 |
| 4081 | YES I found bad smells The bad smells are: 1. Long method 2. Switch statement 3. Duplicate code (using getPropertyMakerFor() to get ruleThickness) 4. Feature envy (calling multiple methods from pList) 5. Use of RuntimeException to handle an error 6. Unused variables (textShadow and letterSpacing) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | Long method 2 Switch statement 3 Duplicate code (using getPropertyMakerFor() to get ruleThickness) 4 Feature envy (calling multiple methods from pList) 5 Use of RuntimeException to handle an error 6 Unused variables (textShadow and letterSpacing) | t | f | t | 0 | 10762 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 4081 | 10762 | ||
| 4085 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10772 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 1 | 4085 | 10772 |
| 4085 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10772 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 2 | 4085 | 10772 | |
| 4086 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10775 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 4086 | 10775 | ||
| 4086 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Switch statement with multiple cases 4. Use of synpred33_InternalXbaseWithAnnotations() method for multiple if conditions 5. Multiple nested if statements 6. Use of input.LA() and input.index() methods multiple times 7. Use of input.rewind() method multiple times 8. Lack of proper naming conventions for variables and methods 9. Duplicate code within cases 1 and 2 10. Unclear and confusing method description and functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Feature envy3 Switch statement with multiple cases4 Use of synpred33_InternalXbaseWithAnnotations() method for multiple if conditions 5 Multiple nested if statements 6 Use of inputLA() and inputindex() methods multiple times 7 Use of inputrewind() method multiple times 8 Lack of proper naming conventions for variables and methods 9 Duplicate code within cases | t | f | t | 0 | 10775 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 4086 | 10775 | ||
| 4088 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
long method | long method | t | t | t | 0 | 10777 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 4088 | 10777 | ||
| 4088 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10777 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 4088 | 10777 | ||
| 4092 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 10781 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 4092 | 10781 | ||
| 4092 | that I can see. This seems like pretty well written code~! | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 10781 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 2 | 4092 | 10781 | ||
| 4093 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | data class | t | t | f | 0 | 10786 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 4093 | 10786 | ||
| 4109 | opens = new Open[count]; YES I found bad smells. The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 10822 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 2 | 4109 | 10822 |
| 4110 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | long method | t | t | f | long method | data class | 0 | 10825 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 1 | 4110 | 10825 |
| 4110 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10825 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 2 | 4110 | 10825 |
| 4111 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | long method | t | t | t | 0 | 10827 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 4111 | 10827 | ||
| 4111 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Data class (lack of encapsulation) 5. Spaghetti code (multiple levels of nesting) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method2 Duplicate code3 Feature envy4 Data class (lack of encapsulation)5 Spaghetti code (multiple levels of nesting) | t | f | t | 0 | 10827 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 4111 | 10827 | ||
| 4113 | {"answer": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 10831 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 | 1 | 4113 | 10831 | |
| 4113 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Large class 4. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } } |
data class | Long method2 Feature envy3 Large class4 Long parameter list | t | f | f | . Long method2. Feature envy3. Large class4. Long parameter list | data class | 0 | 10831 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 | 2 | 4113 | 10831 |
| 4135 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | f | f | f | data class | 0 | 10881 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 2 | 4135 | 10881 | ||
| 4135 | { "response": "YES I found bad smells, the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | 1. data class | t | t | t | 0 | 10881 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 1 | 4135 | 10881 | ||
| 4138 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10899 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 4138 | 10899 |
| 4181 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | long method | t | t | t | 0 | 11002 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 1 | 4181 | 11002 | ||
| 4181 | YES I found bad smells. The bad smells are: 1. Long method 2. Magic number (the use of specific numbers without explanation) 3. Duplicate code (the repeated switch statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | Long method2 Magic number (the use of specific numbers without explanation)3 Duplicate code (the repeated switch statement) | t | f | t | 0 | 11002 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 2 | 4181 | 11002 | ||
| 4197 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | data class | t | t | t | 0 | 11045 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 4197 | 11045 | ||
| 4197 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11045 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 4197 | 11045 |
| 4205 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
long method | long method | t | t | t | 0 | 11065 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 1 | 4205 | 11065 | ||
| 4205 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11065 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 2 | 4205 | 11065 | |
| 4211 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11086 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 4211 | 11086 |
| 4211 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 11086 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 4211 | 11086 | |
| 4213 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 11089 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 4213 | 11089 | |
| 4213 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code/repetitive code 4. Magic numbers 5. Poor variable naming (e.g. "p") 6. Nested if statements 7. Comments that don't add value or are unnecessary 8. Inconsistent formatting (indentation, spacing) 9. Method with too many responsibilities (violating single responsibility principle) 10. Potential exception handling spaghetti code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | Long method2 Feature envy3 Duplicate code/repetitive code4 Magic numbers5 Poor variable naming (eg "p")6 Nested if statements7 Comments that don't add value or are unnecessary8 Inconsistent formatting (indentation, spacing)9 Method with too many responsibilities (violating single responsibility principle) | t | f | t | spacing)9. Method with too many responsibilities (violating single responsibility principle) | 0 | 11089 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 4213 | 11089 | |
| 4219 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11111 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 4219 | 11111 |
| 4219 | YES I found bad smells the bad smells are: 1. Long method 2. Repeated code 3. High complexity 4. Inappropriate levels of abstraction 5. Feature envy 6. Use of magic numbers (e.g. "TRUE" and "JKS") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | Long method2 Repeated code3 High complexity 4 Inappropriate levels of abstraction 5 Feature envy6 Use of magic numbers (eg "TRUE" and "JKS") | t | f | t | 0 | 11111 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 4219 | 11111 | ||
| 4227 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | data class | t | t | t | 0 | 11130 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 4227 | 11130 | ||
| 4227 | { private int[][][] values; public ArrayImageSource( int width, int height, int[][][] values ) { super( width, height ); this.values = values; } public int getRGB( int x, y ) { return values[x][y][0] << 16 | values[x][y][1] << 8 | values[x][y][2]; } protected int height; protected int width; public ImageSource( int width, int height ) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | 6 | values[x][y][ | f | f | f | 6 | values[x][y][ | data class | 0 | 11130 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 4227 | 11130 |
| 4232 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | long method | t | t | t | 0 | 11137 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 4232 | 11137 | ||
| 4232 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy 3. Poor exception handling 4. Overuse of if/else statements 5. Mixing of responsibilities (e.g. handling both proxy and transaction logic in one method) 6. Poor variable naming (e.g. "target", "isNewEm") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long methods2 Feature envy3 Poor exception handling 4 Overuse of if/else statements 5 Mixing of responsibilities (eg handling both proxy and transaction logic in one method) 6 Poor variable naming (eg "target", "isNewEm") | t | f | t | "isNewEm") | 0 | 11137 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 4232 | 11137 | |
| 4237 | { "output": "YES I found bad smells", "detectedBadSmells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | data class | t | t | t | 0 | 11155 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 1 | 4237 | 11155 | ||
| 4237 | YES I found bad smells the bad smells are: 1. Duplicate code (in both constructors) 2. Long method (for Subchannel() constructor and setPitch() method) 3. Feature envy (copy() method accessing fields from another class) 4. Primitive obsession (using primitive data types instead of objects) 5. Misplaced method (equals(), clone(), copy(), and hashCode() methods should not be in Subchannel class but in a separate class for handling comparisons and cloning) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | Duplicate code (in both constructors)2 Long method (for Subchannel() constructor and setPitch() method)3 Feature envy (copy() method accessing fields from another class)4 Primitive obsession (using primitive data types instead of objects)5 Misplaced method (equals(), clone(), copy(), and hashCode() methods should not be in Subchannel class but in a separate class for handling comparisons and cloning) | t | f | f | . Duplicate code (in both constructors)2. Long method (for Subchannel() constructor and setPitch() method)3. Feature envy (copy() method accessing fields from another class)4. Primitive obsession (using primitive data types instead of objects)5. Misplaced method (equals(), clone(), copy(), and hashCode() methods should not be in Subchannel class but in a separate class for handling comparisons and cloning) | data class | 0 | 11155 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 4237 | 11155 |
| 4238 | "My answer: YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy" | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | Long method, 2 Feature envy" | t | f | f | . Long method, 2. Feature envy" | data class | 0 | 11157 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 2 | 4238 | 11157 |
| 4238 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | 1. data class | t | t | t | 0 | 11157 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 1 | 4238 | 11157 | ||
| 4239 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | long method, data class | t | t | t | data class | 0 | 11159 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 4239 | 11159 | |
| 4239 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11159 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 4239 | 11159 | ||
| 4308 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | data class | t | t | t | 0 | 11355 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 4308 | 11355 | ||
| 4308 | YES, I found bad smells in the line below:1.Long method,2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | Long method,2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 11355 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 4308 | 11355 |
| 4314 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11368 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 2 | 4314 | 11368 |
| 4334 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | data class, long method | t | t | t | data class | 0 | 11444 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 1 | 4334 | 11444 | |
| 4334 | YES We found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11444 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 2 | 4334 | 11444 | ||
| 4359 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | 1. long method | t | t | t | 0 | 11504 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 1 | 4359 | 11504 | ||
| 4359 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11504 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 2 | 4359 | 11504 | ||
| 4398 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | long method, data class | t | t | t | data class | 0 | 11629 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 4398 | 11629 | |
| 4398 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11629 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 4398 | 11629 | ||
| 4412 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 11683 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 4412 | 11683 |
| 4412 | return 1. None YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | NoneYES I found bad smellsThe bad smells are: | t | f | f | . NoneYES I found bad smellsThe bad smells are: | feature envy | 0 | 11683 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 4412 | 11683 |
| 4451 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 11797 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 2 | 4451 | 11797 |
| 4451 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 11797 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 1 | 4451 | 11797 |
| 4487 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11883 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 4487 | 11883 | |
| 4487 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11883 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 4487 | 11883 | ||
| 4513 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 11975 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 1 | 4513 | 11975 |
| 4513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11975 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 2 | 4513 | 11975 |
| 4535 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | data class | t | t | t | 0 | 12036 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 4535 | 12036 | ||
| 4535 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy - the toString(), hashCode(), and equals() methods are duplicated from the Object class, indicating a possible design flaw. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long method2 Feature envy - the toString(), hashCode(), and equals() methods are duplicated from the Object class, indicating a possible design flaw | t | f | f | . Long method2. Feature envy - the toString(), hashCode(), and equals() methods are duplicated from the Object class, indicating a possible design flaw. | data class | 0 | 12036 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 4535 | 12036 |
| 4573 | { "message": "YES, I found bad smells", "bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | feature envy, long method | t | t | t | feature envy | 0 | 12153 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 1 | 4573 | 12153 | |
| 4573 | of the above No, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12153 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 2 | 4573 | 12153 | ||
| 4574 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12157 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 4574 | 12157 | ||
| 4574 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12157 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 4574 | 12157 | ||
| 4604 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12251 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 4604 | 12251 |
| 4605 | {"response":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | long method | t | t | t | 0 | 12253 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 4605 | 12253 | ||
| 4605 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12253 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 4605 | 12253 | |
| 4631 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12359 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 4631 | 12359 | ||
| 4631 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12359 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 2 | 4631 | 12359 | ||
| 4664 | { "message": "YES I found bad smells", "bad_smells_found": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12456 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 4664 | 12456 |
| 4664 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12456 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 4664 | 12456 | ||
| 4676 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | long method, data class | t | t | t | data class | 0 | 12504 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 1 | 4676 | 12504 | |
| 4676 | YES I found bad smells the bad smells are: 1. Long method (the method is too long and can be broken down into smaller methods for better readability and maintenance). 2. Feature envy (the method is constantly accessing and manipulating data from external objects, which can indicate that it belongs in a different class). 3. Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain). 4. Nested loops (there are nested for loops, which can decrease performance and make the code more complex). 5. Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code). 6. Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality). 7. Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | Long method (the method is too long and can be broken down into smaller methods for better readability and maintenance)2 Feature envy (the method is constantly accessing and manipulating data from external objects, which can indicate that it belongs in a different class)3 Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain)4 Nested loops (there are nested for loops, which can decrease performance and make the code more complex)5 Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code)6 Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality)7 Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow) | t | f | t | which can indicate that it belongs in a different class).3. Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain).4. Nested loops (there are nested for loops, which can decrease performance and make the code more complex).5. Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code).6. Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality).7. Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow). | 0 | 12504 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 2 | 4676 | 12504 | |
| 4708 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | Long Method | t | f | t | 0 | 12628 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 1 | 4708 | 12628 | ||
| 4708 | YES I found bad smells the bad smells are: 1. Commented-out code 2. Long method 3. Complex conditional logic 4. Feature envy 5. Use of System.out.println() instead of using a logger 6. Magic numbers 7. Lack of proper exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | Commented-out code2 Long method3 Complex conditional logic4 Feature envy5 Use of Systemoutprintln() instead of using a logger6 Magic numbers7 Lack of proper exception handling | t | f | t | 0 | 12628 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 2 | 4708 | 12628 | ||
| 4765 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | 1. long method | t | t | t | 0 | 12825 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 4765 | 12825 | ||
| 4765 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12825 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 4765 | 12825 | ||
| 4807 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractPmdReport extends AbstractMavenReport { /** * The output directory for the intermediate XML report. */ @Parameter( property = "project.build.directory", required = true ) protected File targetDirectory; /** * The output directory for the final HTML report. Note that this parameter is only evaluated if the goal is run * directly from the command line or during the default lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is used instead. */ @Parameter( property = "project.reporting.outputDirectory", required = true ) protected File outputDirectory; /** * Site rendering component for generating the HTML report. */ @Component private Renderer siteRenderer; /** * The project to analyse. */ @Parameter( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * Set the output format type, in addition to the HTML report. Must be one of: "none", "csv", "xml", "txt" or the * full class name of the PMD renderer to use. See the net.sourceforge.pmd.renderers package javadoc for available * renderers. XML is required if the pmd:check goal is being used. */ @Parameter( property = "format", defaultValue = "xml" ) protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is * being used. */ @Parameter( property = "linkXRef", defaultValue = "true" ) private boolean linkXRef; /** * Location of the Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref" ) private File xrefLocation; /** * Location of the Test Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) private File xrefTestLocation; /** * A list of files to exclude from checking. Can contain Ant-style wildcards and double wildcards. Note that these * exclusion patterns only operate on the path of a source file relative to its source root directory. In other * words, files are excluded based on their package and/or class name. If you want to exclude entire source root * directories, use the parameter excludeRoots instead. * * @since 2.2 */ @Parameter private List excludes; /** * A list of files to include from checking. Can contain Ant-style wildcards and double wildcards. Defaults to * **\/*.java. * * @since 2.2 */ @Parameter private List includes; /** * Specifies the location of the source directories to be used for PMD. * Defaults to project.compileSourceRoots. * @since 3.7 */ @Parameter( defaultValue = "${project.compileSourceRoots}" ) private List compileSourceRoots; /** * The directories containing the test-sources to be used for PMD. * Defaults to project.testCompileSourceRoots * @since 3.7 */ @Parameter( defaultValue = "${project.testCompileSourceRoots}" ) private List testSourceRoots; /** * The project source directories that should be excluded. * * @since 2.2 */ @Parameter private File[] excludeRoots; /** * Run PMD on the tests. * * @since 2.2 */ @Parameter( defaultValue = "false" ) protected boolean includeTests; /** * Whether to build an aggregated report at the root, or build individual reports. * * @since 2.2 */ @Parameter( property = "aggregate", defaultValue = "false" ) protected boolean aggregate; /** * The file encoding to use when reading the Java sources. * * @since 2.3 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String sourceEncoding; /** * The file encoding when writing non-HTML reports. * * @since 2.5 */ @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) private String outputEncoding; /** * The projects in the reactor for aggregation report. */ @Parameter( property = "reactorProjects", readonly = true ) protected List reactorProjects; /** * Whether to include the xml files generated by PMD/CPD in the site. * * @since 3.0 */ @Parameter( defaultValue = "false" ) protected boolean includeXmlInSite; /** * Skip the PMD/CPD report generation if there are no violations or duplications found. Defaults to * true. * * @since 3.1 */ @Parameter( defaultValue = "true" ) protected boolean skipEmptyReport; /** * File that lists classes and rules to be excluded from failures. * For PMD, this is a properties file. For CPD, this * is a text file that contains comma-separated lists of classes * that are allowed to duplicate. * * @since 3.7 */ @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) protected String excludeFromFailureFile; /** The files that are being analyzed. */ protected Map filesToProcess; /** * {@inheritDoc} */ @Override protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ @Override protected Renderer getSiteRenderer() { return siteRenderer; } protected String constructXRefLocation( boolean test ) { String location = null; if ( linkXRef ) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = PathTool.getRelativePath( outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath() ); if ( StringUtils.isEmpty( relativePath ) ) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); if ( xrefLoc.exists() ) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; } else { // Not yet generated - check if the report is on its way @SuppressWarnings( "unchecked" ) List reportPlugins = project.getReportPlugins(); for ( ReportPlugin plugin : reportPlugins ) { String artifactId = plugin.getArtifactId(); if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) { location = relativePath; } } } if ( location == null ) { getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); } } return location; } /** * Convenience method to get the list of files where the PMD tool will be executed * * @return a List of the files where the PMD tool will be executed * @throws IOException If an I/O error occurs during construction of the * canonical pathnames of the files */ protected Map getFilesToProcess() throws IOException { if ( aggregate && !project.isExecutionRoot() ) { return Collections.emptyMap(); } if ( excludeRoots == null ) { excludeRoots = new File[0]; } Collection excludeRootFiles = new HashSet<>( excludeRoots.length ); for ( File file : excludeRoots ) { if ( file.isDirectory() ) { excludeRootFiles.add( file ); } } List directories = new ArrayList<>(); if ( null == compileSourceRoots ) { compileSourceRoots = project.getCompileSourceRoots(); } if ( compileSourceRoots != null ) { for ( String root : compileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); } } } if ( null == testSourceRoots ) { testSourceRoots = project.getTestCompileSourceRoots(); } if ( includeTests ) { if ( testSourceRoots != null ) { for ( String root : testSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( project, sroot, testXref ) ); } } } } if ( aggregate ) { for ( MavenProject localProject : reactorProjects ) { @SuppressWarnings( "unchecked" ) List localCompileSourceRoots = localProject.getCompileSourceRoots(); for ( String root : localCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); } } if ( includeTests ) { @SuppressWarnings( "unchecked" ) List localTestCompileSourceRoots = localProject.getTestCompileSourceRoots(); for ( String root : localTestCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); } } } } } String excluding = getExcludes(); getLog().debug( "Exclusions: " + excluding ); String including = getIncludes(); getLog().debug( "Inclusions: " + including ); Map files = new TreeMap<>(); for ( PmdFileInfo finfo : directories ) { getLog().debug( "Searching for files in directory " + finfo.getSourceDirectory().toString() ); File sourceDirectory = finfo.getSourceDirectory(); if ( sourceDirectory.isDirectory() && !isDirectoryExcluded( excludeRootFiles, sourceDirectory ) ) { List newfiles = FileUtils.getFiles( sourceDirectory, including, excluding ); for ( File newfile : newfiles ) { files.put( newfile.getCanonicalFile(), finfo ); } } } return files; } private boolean isDirectoryExcluded( Collection excludeRootFiles, File sourceDirectoryToCheck ) { boolean returnVal = false; for ( File excludeDir : excludeRootFiles ) { try { if ( sourceDirectoryToCheck.getCanonicalPath().startsWith( excludeDir.getCanonicalPath() ) ) { getLog().debug( "Directory " + sourceDirectoryToCheck.getAbsolutePath() + " has been excluded as it matches excludeRoot " + excludeDir.getAbsolutePath() ); returnVal = true; break; } } catch ( IOException e ) { getLog().warn( "Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e ); } } return returnVal; } /** * Gets the comma separated list of effective include patterns. * * @return The comma separated list of effective include patterns, never null. */ private String getIncludes() { Collection patterns = new LinkedHashSet<>(); if ( includes != null ) { patterns.addAll( includes ); } if ( patterns.isEmpty() ) { patterns.add( "**/*.java" ); } return StringUtils.join( patterns.iterator(), "," ); } /** * Gets the comma separated list of effective exclude patterns. * * @return The comma separated list of effective exclude patterns, never null. */ private String getExcludes() { Collection patterns = new LinkedHashSet<>( FileUtils.getDefaultExcludesAsList() ); if ( excludes != null ) { patterns.addAll( excludes ); } return StringUtils.join( patterns.iterator(), "," ); } protected boolean isHtml() { return "html".equals( format ); } protected boolean isXml() { return "xml".equals( format ); } /** * {@inheritDoc} */ @Override public boolean canGenerateReport() { if ( aggregate && !project.isExecutionRoot() ) { return false; } if ( "pom".equals( project.getPackaging() ) && !aggregate ) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures if ( isXml() ) { return true; } try { filesToProcess = getFilesToProcess(); if ( filesToProcess.isEmpty() ) { return false; } } catch ( IOException e ) { getLog().error( e ); } return true; } /** * {@inheritDoc} */ @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } protected String getSourceEncoding() { return sourceEncoding; } /** * Gets the effective reporting output files encoding. * * @return The effective reporting output file encoding, never null. * @since 2.5 */ protected String getOutputEncoding() { return ( outputEncoding != null ) ? outputEncoding : ReaderFactory.UTF_8; } static String getPmdVersion() { try { return (String) PMD.class.getField( "VERSION" ).get( null ); } catch ( IllegalAccessException e ) { throw new RuntimeException( "PMD VERSION field not accessible", e ); } catch ( NoSuchFieldException e ) { throw new RuntimeException( "PMD VERSION field not found", e ); } } } |
data class | data class, long method | t | t | t | long method | 0 | 13040 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-pmd-plugin/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java/#L52-L553 | 1 | 4807 | 13040 | |
| 4881 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13281 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 1 | 4881 | 13281 | ||
| 4881 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13281 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 2 | 4881 | 13281 | ||
| 4928 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13480 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 2 | 4928 | 13480 |
| 4928 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
data class | f | f | f | data class | 0 | 13480 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 1 | 4928 | 13480 | ||
| 4956 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 13562 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 4956 | 13562 | ||
| 4956 | { "status": "success", "message": "YES, I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13562 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 4956 | 13562 |
| 4998 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
data class | data class, long method | t | t | t | long method | 0 | 13726 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 4998 | 13726 | |
| 5004 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13760 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5004 | 13760 | ||
| 5004 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13760 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5004 | 13760 | ||
| 5008 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | long method | t | t | f | long method | data class | 0 | 13770 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 1 | 5008 | 13770 |
| 5012 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | long method | t | t | t | 0 | 13779 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 5012 | 13779 | ||
| 5012 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Tight coupling 5. Magic numbers 6. Dead code 7. Exception handling 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Long method 2 Duplicate code 3 Feature envy 4 Tight coupling 5 Magic numbers 6 Dead code 7 Exception handling 8 Lack of comments/documentation | t | f | t | 0 | 13779 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 5012 | 13779 | ||
| 5025 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 13928 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 2 | 5025 | 13928 |
| 5025 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | long method, data class | t | t | t | long method | 0 | 13928 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 1 | 5025 | 13928 | |
| 5028 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | data class | t | t | t | 0 | 13962 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 1 | 5028 | 13962 | ||
| 5028 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13962 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 2 | 5028 | 13962 |
| 5084 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14204 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 5084 | 14204 |
| 5090 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | data class | t | t | t | 0 | 14228 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 1 | 5090 | 14228 | ||
| 5090 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 14228 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 2 | 5090 | 14228 |
| 5148 | { "answer": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | data class | t | t | t | 0 | 14405 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 1 | 5148 | 14405 | ||
| 5148 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14405 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 2 | 5148 | 14405 |
| 5153 | I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 14424 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 2 | 5153 | 14424 | ||
| 5153 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 14424 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 1 | 5153 | 14424 | ||
| 5166 | {"message": "YES I found bad smells\nthe bad smells are: 4. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | 4. long method | t | t | t | 0 | 14457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 5166 | 14457 | ||
| 5166 | :Parse the thrift exception and identify if exception belongs to workspace project or else Args: isAiravataException (bool) An object handle Returns: string YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Duplicated code2 Long method3 Feature envy | t | f | t | 0 | 14457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 5166 | 14457 | ||
| 5180 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
data class | data class, long method | t | t | t | long method | 0 | 14486 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 1 | 5180 | 14486 | |
| 5180 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession 5. Divergent change 6. Temporary field 7. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
data class | Long method2 Feature envy3 Data class4 Primitive obsession5 Divergent change6 Temporary field7 Lazy class | t | f | t | 0 | 14486 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 2 | 5180 | 14486 | ||
| 5182 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | "NO, I did not find any bad smell"} | f | f | f | "NO, I did not find any bad smell"} | long method | 0 | 14493 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xtext.ui.examples/projects/domainmodel/org.eclipse.xtext.example.domainmodel.ide/src-gen/org/eclipse/xtext/example/domainmodel/ide/contentassist/antlr/internal/InternalDomainmodelParser.java/#L62002-L62027 | 1 | 5182 | 14493 |
| 5189 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 14509 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5189 | 14509 | ||
| 5189 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14509 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5189 | 14509 | |
| 5190 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14510 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5190 | 14510 | ||
| 5190 | NO, I did not find any bad smell in this code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14510 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5190 | 14510 | ||
| 5193 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | 1. long method | t | t | t | 0 | 14519 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 1 | 5193 | 14519 | ||
| 5193 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14519 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 2 | 5193 | 14519 | ||
| 5261 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14710 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 5261 | 14710 |
| 5271 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | long method | t | t | t | 0 | 14741 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 5271 | 14741 | ||
| 5271 | * * YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method2 Feature envy | t | f | t | 0 | 14741 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 5271 | 14741 | ||
| 5274 | I found bad smells. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 14746 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5274 | 14746 | ||
| 5274 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 14746 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5274 | 14746 | ||
| 5275 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14747 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5275 | 14747 | ||
| 5275 | . There are no major bad smells in this code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14747 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5275 | 14747 | ||
| 5278 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 14761 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 1 | 5278 | 14761 |
| 5278 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Message is both Serializable and has additional methods that write/read from ByteBuffer. This is a violation of the Single Responsibility Principle. 4. Mix of field-based and property-based access. 5. Mix of private and public fields without clear distinction. 6. Use of hardcoded values instead of constants. 7. Unnecessary comments and empty methods that serve no purpose. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | Long method2 Feature envy3 Message is both Serializable and has additional methods that write/read from ByteBuffer This is a violation of the Single Responsibility Principle4 Mix of field-based and property-based access5 Mix of private and public fields without clear distinction6 Use of hardcoded values instead of constants7 Unnecessary comments and empty methods that serve no purpose | t | f | f | . Long method2. Feature envy3. Message is both Serializable and has additional methods that write/read from ByteBuffer. This is a violation of the Single Responsibility Principle.4. Mix of field-based and property-based access.5. Mix of private and public fields without clear distinction.6. Use of hardcoded values instead of constants.7. Unnecessary comments and empty methods that serve no purpose. | data class | 0 | 14761 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 2 | 5278 | 14761 |
| 5324 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | 1. long method | t | t | t | 0 | 14946 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 5324 | 14946 | ||
| 5324 | YES I found bad smells The bad smells are: 1.Feature envy 2.Long method 3.Inconsistent spacing and indentation 4.Magic numbers (PigConfiguration.PIG_ATS_ENABLED) 5.Multiple conditionals in one line (Boolean.parseBoolean calls) 6.Coupled classes (PigATSClient) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Feature envy2Long method3Inconsistent spacing and indentation4Magic numbers (PigConfigurationPIG_ATS_ENABLED)5Multiple conditionals in one line (BooleanparseBoolean calls)6Coupled classes (PigATSClient) | t | f | t | 0 | 14946 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 5324 | 14946 | ||
| 5325 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | f | f | f | long method | 0 | 14949 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 5325 | 14949 | ||
| 5325 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | long method | t | t | t | 0 | 14949 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 5325 | 14949 | ||
| 5381 | { "output": "YES I found bad smells", "the bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | data class | t | t | t | 0 | 15120 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 5381 | 15120 | ||
| 5381 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 15120 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 5381 | 15120 |
| 5382 | { "output": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | data class | t | t | t | 0 | 15137 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 5382 | 15137 | ||
| 5382 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 15137 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 5382 | 15137 |
| 5390 | , NO i did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 15151 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 5390 | 15151 | ||
| 5390 | { "response": "YES, I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15151 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 5390 | 15151 |
| 5391 | { "message": "Please share the Java code for analysis." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | Not specified | f | f | f | false | 0 | 15152 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 5391 | 15152 | |
| 5391 | of the function below have bad smells NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 15152 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 5391 | 15152 | ||
| 5395 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 15164 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 5395 | 15164 | ||
| 5396 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Not specified | f | f | f | false | 0 | 15166 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 1 | 5396 | 15166 | |
| 5396 | YES I have found bad smells the bad smells are:Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Feature envy | t | f | t | 0 | 15166 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 2 | 5396 | 15166 | ||
| 5400 | found (provided Javadoc comments without adding unecessary white space bloat). NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 15175 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 5400 | 15175 | ||
| 5400 | { "message": "Please provide the Java code you would like me to check for code smells." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | Not specified | f | f | f | false | 0 | 15175 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 5400 | 15175 | |
| 5401 | found: "NO, I did not find any bad smell" | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | "NO, I did not find any bad smell" | f | f | f | "NO, I did not find any bad smell" | long method | 0 | 15176 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 5401 | 15176 |
| 5407 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 15185 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 5407 | 15185 | |
| 5419 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | data class, long method | t | t | t | long method | 0 | 15209 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 1 | 5419 | 15209 | |
| 5419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15209 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 2 | 5419 | 15209 |
| 5444 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15311 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 1 | 5444 | 15311 |
| 5444 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 15311 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 2 | 5444 | 15311 | ||
| 5480 | NO, I did not find any bad smells. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | f | f | f | long method | 0 | 1191 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5480 | 1191 | ||
| 5481 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 1263 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 2 | 5481 | 1263 | |
| 5481 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 1263 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 1 | 5481 | 1263 | |
| 5490 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 1877 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5490 | 1877 |
| 5490 | YES I found bad smells. the bad smells are: 1. Long method, 2. Data class. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long method, 2 Data class | t | f | t | 2. Data class. | 0 | 1877 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5490 | 1877 | |
| 5494 | NO, I did not find any bad smell. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | f | f | f | long method | 0 | 2683 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 1 | 5494 | 2683 | ||
| 5494 | {"output": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 2683 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 2 | 5494 | 2683 |
| 5498 | YES I found bad smells. The bad smells are: Long method. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
long method | Long method | t | f | t | 0 | 3000 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5498 | 3000 | ||
| 5499 | YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
feature envy | Long Method, 2 Feature Envy | t | f | t | . Long Method | 0 | 3001 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5499 | 3001 | |
| 5500 | { "response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final Iterator applyAll(final S start, final Traversal.Admin traversal) { traversal.reset(); traversal.addStart(traversal.getTraverserGenerator().generate(start, traversal.getStartStep(), 1l)); return traversal; // flatMap } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 3063 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalUtil.java/#L99-L103 | 2 | 5500 | 3063 | |
| 5500 | YES, I found bad smells in the following code. The bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final Iterator applyAll(final S start, final Traversal.Admin traversal) { traversal.reset(); traversal.addStart(traversal.getTraverserGenerator().generate(start, traversal.getStartStep(), 1l)); return traversal; // flatMap } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3063 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalUtil.java/#L99-L103 | 1 | 5500 | 3063 | ||
| 5507 | {"message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3711 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5507 | 3711 | |
| 5507 | The bad smells are: 1.Long Method, 2.Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long Method, 2Feature Envy | f | f | t | 2.Feature Envy | 0 | 3711 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5507 | 3711 | |
| 5508 | This is the unfortunate code spaced in the file YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3712 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5508 | 3712 | ||
| 5515 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Magic number", "Non-descriptive method or variable names", "Nested block", "Complex conditional logic", "Duplicate code"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | long method, magic number, non-descriptive method or variable names, nested block, complex conditional logic, duplicate code | t | t | t | magic number, non-descriptive method or variable names, nested block, complex conditional logic, duplicate code | 0 | 4260 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5515 | 4260 | |
| 5515 | YES I found bad smells the bad smells are: Long method, Feature envy, Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Long method, Feature envy, Data class | t | f | t | Feature envy, Data class | 0 | 4260 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5515 | 4260 | |
| 5526 | { "response": "YES I found bad smells", "details": "the bad smells are:", "bad_smells": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void asJson(OutputStream out, Map data) throws HiveException { try { new ObjectMapper().writeValue(out, data); } catch (IOException e) { throw new HiveException("Unable to convert to json", e); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 5595 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/JsonMetaDataFormatter.java/#L76-L84 | 2 | 5526 | 5595 | |
| 5531 | { "message": "YES I found bad smells", "bad smells": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 5816 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5531 | 5816 | |
| 5531 | YES, I found bad smells the bad smells are: 1. Long method 2. Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long method2 Data class | t | f | t | 0 | 5816 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5531 | 5816 | ||
| 5535 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 6189 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5535 | 6189 |
| 5535 | YES I found bad smells the bad smells are: Data class, Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Data class, Long method | t | f | t | Data class | 0 | 6189 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5535 | 6189 | |
| 5536 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6190 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5536 | 6190 |
| 5536 | YES I found bad smells. The bad smells are: 1. Feature Envy; 2. Data Class. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
feature envy | Feature Envy;2 Data Class | t | f | t | 0 | 6190 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5536 | 6190 | ||
| 5537 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Function keyFunction, Function valueFunction) { checkNotNull(keyFunction, "keyFunction"); checkNotNull(valueFunction, "valueFunction"); return Collector.of( ImmutableSetMultimap::builder, (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)), ImmutableSetMultimap.Builder::combine, ImmutableSetMultimap.Builder::build); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 6246 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/collect/ImmutableSetMultimap.java/#L86-L96 | 2 | 5537 | 6246 |
| 5537 | YES, I found bad smells. The bad smells are: 1. Long method. 2. Feature envy. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Function keyFunction, Function valueFunction) { checkNotNull(keyFunction, "keyFunction"); checkNotNull(valueFunction, "valueFunction"); return Collector.of( ImmutableSetMultimap::builder, (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)), ImmutableSetMultimap.Builder::combine, ImmutableSetMultimap.Builder::build); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6246 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/collect/ImmutableSetMultimap.java/#L86-L96 | 1 | 5537 | 6246 | ||
| 5561 | { "output": "YES I found bad smells", "bad smells are": "1.Long method, 2.Feature envy" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | 1.long method, 2.feature envy | t | t | f | 2.feature envy | long method | 0 | 7769 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 2 | 5561 | 7769 |
| 5561 | YES I found bad smells the bad smells are listed in this format: 1. Long method, 2. Data class, 3. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | Long method, 2 Data class, 3 Feature envy | t | f | t | 2. Data class, 3. Feature envy | 0 | 7769 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5561 | 7769 | |
| 5570 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | 1. long method | t | t | f | long method | 0 | 8187 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5570 | 8187 | |
| 5570 | YES I found bad smells The bad smells are: 1. Long method 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Long method2Feature envy | t | f | t | 0 | 8187 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5570 | 8187 | ||
| 5571 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy."} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
feature envy | 1. long method, 2. feature envy. | t | t | f | 1. long method | feature envy | 0 | 8188 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5571 | 8188 |
| 5584 | YES I found bad smells the smells are: 1. Feature envy 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Feature envy2 Long method | t | f | t | 0 | 9276 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5584 | 9276 | ||
| 5585 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 9277 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5585 | 9277 |
| 5585 | YES I found bad smells: Long method, Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 9277 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5585 | 9277 | |
| 5601 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10170 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5601 | 10170 | ||
| 5638 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 10869 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5638 | 10869 |
| 5638 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 10869 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5638 | 10869 | ||
| 5639 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | long method | t | t | t | 0 | 10918 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5639 | 10918 | ||
| 5639 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10918 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5639 | 10918 | ||
| 5640 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10919 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5640 | 10919 |
| 5640 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 10919 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5640 | 10919 |
| 5648 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11201 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5648 | 11201 | |
| 5648 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | f | f | f | long method | 0 | 11201 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5648 | 11201 | ||
| 5649 | {"response": "YES I found bad smells\nthe bad smells are:\n1. Long method\n2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | \n1. long method\n2. feature envy | t | t | f | long method | 0 | 11206 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 2 | 5649 | 11206 | |
| 5649 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Long method | t | f | t | 0 | 11206 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5649 | 11206 | ||
| 5676 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy", "Long parameter list" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | long method, feature envy, long parameter list | t | t | t | feature envy, long parameter list | 0 | 11770 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5676 | 11770 | |
| 5676 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Long method | t | f | t | 0 | 11770 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5676 | 11770 | ||
| 5690 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Long parameter list" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | long method, long parameter list | t | t | t | long parameter list | 0 | 12064 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 2 | 5690 | 12064 | |
| 5709 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12658 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5709 | 12658 | |
| 5709 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | f | f | f | long method | 0 | 12658 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5709 | 12658 | ||
| 5710 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | 1. long method | t | t | f | long method | 0 | 12666 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5710 | 12666 | |
| 5710 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12666 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5710 | 12666 | ||
| 5713 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12782 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5713 | 12782 | |
| 5713 | Yes, I found bad smells. The bad smells are: 1. Long method, 2.Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Long method, 2Feature Envy | t | f | t | 2.Feature Envy | 0 | 12782 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5713 | 12782 | |
| 5714 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12783 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5714 | 12783 | ||
| 5722 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | Long method2 Data class3 Feature envy | t | f | t | 0 | 12971 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 1 | 5722 | 12971 | ||
| 5732 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 13493 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5732 | 13493 |
| 5732 | YES I found bad smells the bad smells are: 1. Data Class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Data Class | t | f | f | . Data Class | long method | 0 | 13493 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5732 | 13493 |
| 5741 | YES I found bad smells the bad smells are: 1. Data Class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Data Class | t | f | f | . Data Class | long method | 0 | 14081 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5741 | 14081 |
| 5744 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method | t | t | t | 0 | 14137 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5744 | 14137 | ||
| 5744 | YES I found bad smells the bad smells are: 1. Long method, 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14137 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5744 | 14137 | |
| 5745 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | f | f | f | feature envy | 0 | 14138 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5745 | 14138 | ||
| 5745 | { "response": "YES I found bad smells", "the bad smells are": { "1. Long method": true, "2. Feature envy": true } } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | 1. long method: true, 2. feature envy: true | t | t | t | 1. long method: true | 0 | 14138 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5745 | 14138 | |
| 5756 | YES I found bad smells the bad smells are: 1.Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long Method | t | f | t | 0 | 14501 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5756 | 14501 | ||
| 5757 | NO, I did not find any bad smell. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
feature envy | f | f | f | feature envy | 0 | 14502 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5757 | 14502 | ||
| 5757 | {"response": "YES I found bad smells","bad smells are": ["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
feature envy | 1. long method, 2. feature envy | t | t | f | 1. long method | feature envy | 0 | 14502 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5757 | 14502 |
| 5759 | {"message": "YES, I found bad smells", "bad smells are": ["Long method", "Long parameter list"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, long parameter list | t | t | t | long parameter list | 0 | 14515 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5759 | 14515 | |
| 5759 | YES, I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 14515 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5759 | 14515 | ||
| 5760 | NO, I did not find any bad smell. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | f | f | f | feature envy | 0 | 14516 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5760 | 14516 | ||
| 5760 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14516 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5760 | 14516 | |
| 5763 | YES I found bad smells, the bad smells are: 1. Long method 2. Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
feature envy | Long method2 Data class | t | f | f | . Long method2. Data class | feature envy | 0 | 14545 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5763 | 14545 |
| 5764 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14546 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5764 | 14546 |
| 5764 | YES I found bad smells the bad smells are: 1. Data Class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Data Class | t | f | f | . Data Class | long method | 0 | 14546 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5764 | 14546 |
| 5765 | } YES I found bad smells the bad smells are: 1. Long method, 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14654 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5765 | 14654 | |
| 5766 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
feature envy | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14655 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 2 | 5766 | 14655 |
| 5766 | YES I found bad smells 1. Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
feature envy | Long Method | t | f | f | . Long Method | feature envy | 0 | 14655 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5766 | 14655 |
| 5770 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14810 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5770 | 14810 |
| 5770 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14810 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5770 | 14810 | ||
| 5771 | YES, I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Long method | t | f | t | 0 | 14811 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5771 | 14811 | ||
| 5773 | {"response":"YES I found bad smells","bad smells are:":"1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 14885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5773 | 14885 |
| 5773 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5773 | 14885 | ||
| 5774 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14902 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 2 | 5774 | 14902 |
| 5774 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | f | f | f | long method | 0 | 14902 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5774 | 14902 | ||
| 5777 | {"response": "YES I found bad smells", "bad smells are:": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method | t | t | t | 0 | 15213 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5777 | 15213 | ||
| 5777 | YES I found bad smells the bad smells are: 1. Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long Method | t | f | t | 0 | 15213 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5777 | 15213 | ||
| 5778 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 15214 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5778 | 15214 |
| 5778 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | f | f | f | feature envy | 0 | 15214 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5778 | 15214 | ||
| 5781 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method | t | t | t | 0 | 15317 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5781 | 15317 | ||
| 5781 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 15317 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5781 | 15317 | ||
| 5782 | {"response": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 15318 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5782 | 15318 |
| 5782 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 15318 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5782 | 15318 |
(3661 rows)